JavaScript 提供多種遍歷語法。最原始的寫法就是for
循環。es6
let arr = [1,2,3,4,5]; for (var index = 0; index < arr.length; index++) { console.log(myArray[index]); // 1 2 3 4 5 }
缺點:這種寫法比較麻煩數組
數組提供內置的forEach
方法數據結構
let arr = [1,2,3,4,5]; arr.forEach((element,index) => { console.log(element); // 1 2 3 4 5 });
缺點:這種寫法的問題在於,沒法中途跳出forEach
循環,break
命令或return
命令都不能奏效。設計
for…in 用於遍歷對象全部的可枚舉屬性,功能相似於Object.keys。code
let obj = { name: 'cloud', phone: '157xxxx2065' } for (let prop in obj) { console.log(prop); // name phone }
可能有朋友會問,不可枚舉的對象有哪些呢? 好比constructor,數組的length就屬於不可枚舉屬性。對象
let arr = [10, 20, 30, 40, 50]; for (let prop in arr) { console.log(prop); // '0' '1' '2' '3' '4' }
缺點:索引
for...in
循環是以字符串做爲鍵名「0」、「1」、「2」等等。for...in
循環主要是爲遍歷對象而設計的,不適用於遍歷數組
for…of是ES6新增的遍歷方式,它提供了統一的遍歷機制。全部實現了[Symbol.iterator]接口的對象均可以被遍歷。for...of
循環能夠使用的範圍包括數組、Set 和 Map 結構、某些相似數組的對象(好比arguments
對象、DOM NodeList 對象)、Generator 對象,以及字符串接口
優勢:ip
for...in
同樣的簡潔語法,可是沒有for...in
那些缺點forEach
方法,它能夠與break
、continue
和return
配合使用下面是一個使用break語句,跳出for...of
循環的例子。ci
for (var n of fibonacci) { if (n > 1000) break; console.log(n); }
上面的例子,會輸出斐波納契數列小於等於1000的項。若是當前項大於1000,就會使用break
語句跳出for...of
循環。
entries
返回一個遍歷器對象,用來遍歷[鍵名, 鍵值]
組成的數組。對於數組,鍵名就是索引值;對於 Set,鍵名與鍵值相同。Map 結構的 Iterator 接口,默認就是調用entries
方法。keys
返回一個遍歷器對象,用來遍歷全部的鍵名。values
返回一個遍歷器對象,用來遍歷全部的鍵值。// demo let arr = ['a', 'b', 'c']; for (let pair of arr.entries) { console.log(pair); } // [0, 'a'] // [1, 'b'] // [2, 'c']
相似數組的對象包括好幾類。下面是for...of
循環用於字符串、DOM NodeList 對象、arguments
對象的例子。
// 字符串 let str = "hello"; for (let s of str) { console.log(s); // h e l l o } // DOM NodeList對象 let paras = document.querySelectorAll("p"); for (let p of paras) { p.classList.add("test"); } // arguments對象 function printArgs { for (let x of arguments) { console.log(x); } } printArgs('a', 'b'); // 'a' // 'b'
並非全部相似數組的對象都具備 Iterator 接口,一個簡便的解決方法,就是使用Array.from
方法將其轉爲數組。
let arrayLike = { length: 2, 0: 'a', 1: 'b' }; // 報錯 for (let x of arrayLike) { console.log(x); } // 正確 for (let x of Array.from(arrayLike)) { console.log(x); // 'a' // 'b' }
對於普通的對象,for...of
結構不能直接使用,會報錯,必須部署了 Iterator 接口後才能使用。
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 is not iterable
解決方法是,使用Object.keys
方法將對象的鍵名生成一個數組,而後遍歷這個數組。