JavaScript 原有的for...in循環(huán),只能獲得對(duì)象的鍵名,不能直接獲取鍵值。ES6 提供for...of循環(huán),允許遍歷獲得鍵值。
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循環(huán)調(diào)用遍歷器接口,數(shù)組的遍歷器接口只返回具有數(shù)字索引的屬性
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"
}
對(duì)于普通的對(duì)象,for...of結(jié)構(gòu)不能直接使用,會(huì)報(bào)錯(cuò),必須部署了 Iterator 接口后才能使用。但是,這樣情況下,for...in循環(huán)依然可以用來(lái)遍歷鍵名。
for...of循環(huán)可以使用的范圍包括數(shù)組、Set 和 Map 結(jié)構(gòu)、某些類(lèi)似數(shù)組的對(duì)象(比如arguments對(duì)象、DOM NodeList 對(duì)象)、后文的 Generator 對(duì)象,以及字符串。
總結(jié)
一、最原始的寫(xiě)法for循環(huán)。
for (var index = 0; index < myArray.length; index++) {
console.log(myArray[index]);
}
這種寫(xiě)法比較麻煩,因此數(shù)組提供內(nèi)置的forEach方法。
二、forEach方法。
myArray.forEach(function (value) {
console.log(value);
});
這種寫(xiě)法的問(wèn)題在于,無(wú)法中途跳出forEach循環(huán),break命令或return命令都不能奏效。
三、for...in循環(huán)。
for...in循環(huán)可以遍歷數(shù)組的鍵名。
for (var index in myArray) {
console.log(myArray[index]);
}
for...in循環(huán)有幾個(gè)缺點(diǎn)。
- 數(shù)組的鍵名是數(shù)字,但是for...in循環(huán)是以字符串作為鍵名“0”、“1”、“2”等等。
- for...in循環(huán)不僅遍歷數(shù)字鍵名,還會(huì)遍歷手動(dòng)添加的其他鍵,甚至包括原型鏈上的鍵。
- 某些情況下,for...in循環(huán)會(huì)以任意順序遍歷鍵名。
總之,for...in循環(huán)主要是為遍歷對(duì)象而設(shè)計(jì)的,不適用于遍歷數(shù)組。
四、for...of循環(huán)。
for...of循環(huán)相比上面幾種做法,有一些顯著的優(yōu)點(diǎn)。
for (let value of myArray) {
console.log(value);
}
- 有著同for...in一樣的簡(jiǎn)潔語(yǔ)法,但是沒(méi)有for...in那些缺點(diǎn)。
- 不同于forEach方法,它可以與break、continue和return配合使用。
- 提供了遍歷所有數(shù)據(jù)結(jié)構(gòu)的統(tǒng)一操作接口。
下面是一個(gè)使用 break 語(yǔ)句,跳出for...of循環(huán)的例子。
for (var n of fibonacci) {
if (n > 1000)
break;
console.log(n);
}
上面的例子,會(huì)輸出斐波納契數(shù)列小于等于 1000 的項(xiàng)。如果當(dāng)前項(xiàng)大于 1000,就會(huì)使用break語(yǔ)句跳出for...of循環(huán)。