首页 > 代码库 > [ES6] 19. for ... of

[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// standardvar engines = Set(["Gecko", "Trident", "Webkit", "Webkit"]);for (var e of engines) {    console.log(e);}// Gecko// Trident// Webkitvar 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

[ES6] 19. for ... of