[ES6] 19. for ... of

In ES5, we have for ... in


 

var phones = ["iPhone", "Nexus", "Nokia"];

for(i in phones){
    console.log(phones[i]);
}

//iPhone
//Nexus
//Nokia

What we get from for...in is index of array.

 

In ES6, for ... of can get value from array:


 

var phones = ["iPhone", "Nexus", "Nokia"];

for(phone of phones){
    console.log(phone);
}

//iPhone
//Nexus
//Nokia

 

Using for...of on object:


 

var es6 = {
  edition: 6,
  committee: "TC39",
  standard: "ECMA-262"
};

for (e in es6) {
  console.log(e);
}
// edition
// committee
// standard

var engines = Set(["Gecko", "Trident", "Webkit", "Webkit"]);
for (var e of engines) {
    console.log(e);
}
// Gecko
// Trident
// Webkit

var es6 = new Map();
es6.set("edition", 6);
es6.set("committee", "TC39");
es6.set("standard", "ECMA-262");
for (var [name, value] of es6) { console.log(name + ": " + value); } // edition: 6 // committee: TC39 // standard: ECMA-262

 

See more: http://javascript.ruanyifeng.com/advanced/ecmascript6.html#toc17

posted @ 2015-01-02 05:44  Zhentiw  阅读(635)  评论(0编辑  收藏  举报