Přejít na menu

Javascript cheatsheet

Správa článků

Vyhledávání Vyhledávání
3.1.2015 21:21
,
Počet přečtení: 943
Obrázek ke článku Javascript cheatsheet

Javascript syntax and basic function usage examples.

Variables

var functionScopeVariable; // VAR has entire enclosing function scope
let blockScopeVariable; // LET has the scope in actual block

Data types

null

Iterations

Good overview on StackOverflow.

forEach function

var a = ["Novak", "Roger", "Rafa"];
a.forEach(function(entry) {
    console.log(entry);
});

basic for loop

for (i = 0; i < a.length; i++) ..    // basic notation

for..in loop

For iterationg over object properties; works also for arrays. Until ES6 the order is not guaranteed for arrays. It is also necessary to do further checkings (hasOwnProperty etc.).

for (key in a)
    a[key];

for..of loop

Since ES6.

for (val of a) {
    console.log(val);
}

Arrays

var men = ["Rafa", "Roger", "Nole"];
var women = ["Serena", "Maria"];
var players = men.concat(women); // Join two arrays
men.indexOf("Rafa"); // returns 0 (find in array: -1 if not found, else integer position)
men.push("Andy");
delete men["Rafa"];
var res = "Lazy dog jumps".split(" "); // ["Lazy", "dog", "jumps"]
var joinedWithComma = men.join(); // "Roger,Nole,Andy"
var joinedOther = men.join(" - "); // "Roger - Nole"
myArray.splice(position, removeCount, newItem)
  example: women.splice(0, 1, "Petra"); // ["Petra", "Maria"]


mutenta

Dicts

Hashable dicts are simple JS objects:

var hashtable = {};
hashtable.foo = "bar";
hashtable['bar'] = "foo";

Objects

Object properties

AccessingmyObject.myProperty

Testing whether the property exist

x.hasOwnProperty('y') // does not include inherited
'y' in x // includes the inherited

Object.keys(myObject);  // get keys of array or object properties names

Strings

Template literals:

let myString = `some string text ${myVariable} another string text`;

"      trim removes whitespaces from both sides!   ".trim(); // "trim removes whitespaces from both sides!"

Regexps

var re = /quick\s(brown)(.+)?(jumps)/ig;
var result = re.exec('The Quick Brown Fox Jumps Over The Lazy Dog');
// result = ["Quick Brown Fox Jumps", "Brown", "Fox", "Jumps"]

Events

deprecated onunload - triggers when user leaves the page; deprecated in jQuery - use onbeforeunload

Vytvořil 3. ledna 2015 ve 21:25:23 mira. Upravováno 155x, naposledy 2. října 2016 v 15:01:01, mira


Diskuze ke článku

Vložení nového komentáře
*
*
*