引自:http://es6.ruanyifeng.com/#docs/iteratores6
for...of
循環能夠代替數組實例的forEach
方法。數組
const arr = ['red', 'green', 'blue']; arr.forEach(function (element, index) { console.log(element); // red green blue console.log(index); // 0 1 2 });
JavaScript 原有的for...in
循環,只能得到對象的鍵名,不能直接獲取鍵值。ES6 提供for...of
循環,容許遍歷得到鍵值。ide
var arr = ['a', 'b', 'c', 'd']; for (let a in arr) { console.log(a); // 0 1 2 3 } for (let a of arr) { console.log(a); // a b c d }
for...of
循環調用遍歷器接口,數組的遍歷器接口只返回具備數字索引的屬性。這一點跟for...in
循環也不同。spa
let arr = [3, 5, 7]; arr.foo = 'hello'; for (let i in arr) { console.log(i); // "0", "1", "2", "foo" } for (let i of arr) { console.log(i); // "3", "5", "7" }
上面代碼中,for...of
循環不會返回數組arr
的foo
屬性。設計
Set 和 Map 結構 循環code
var engines = new 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
對於普通的對象,for...of
結構不能直接使用,會報錯,必須部署了 Iterator 接口後才能使用。可是,這樣狀況下,for...in
循環依然能夠用來遍歷鍵名。對象
let es6 = { edition: 6, committee: "TC39", standard: "ECMA-262" }; for (let e in es6) { console.log(e); } // edition // committee // standard for (let e of es6) { console.log(e); } // TypeError: es6[Symbol.iterator] is not a function
一種解決方法是,使用Object.keys
方法將對象的鍵名生成一個數組,而後遍歷這個數組。blog
for (var key of Object.keys(someObject)) { console.log(key + ': ' + someObject[key]); }
for...in
循環有幾個缺點。索引
for...in
循環是以字符串做爲鍵名「0」、「1」、「2」等等。for...in
循環不只遍歷數字鍵名,還會遍歷手動添加的其餘鍵,甚至包括原型鏈上的鍵。for...in
循環會以任意順序遍歷鍵名。總之,for...in
循環主要是爲遍歷對象而設計的,不適用於遍歷數組。接口