以數(shù)組為例键菱,JavaScript 提供多種遍歷語法穴墅。最原始的寫法就是for循環(huán)。
for (var index = 0; index < myArray.length; index++) {
console.log(myArray[index]);
}
這種寫法比較麻煩,因此數(shù)組提供內(nèi)置的forEach方法亿遂。
myArray.forEach(function (value) {
console.log(value);
});
這種寫法的問題在于,無法中途跳出forEach循環(huán)渺杉,break命令或return命令都不能奏效蛇数。
for...in循環(huán)可以遍歷數(shù)組的鍵名。
for (var index in myArray) {
console.log(myArray[index]);
}
for...in循環(huán)有幾個缺點是越。
數(shù)組的鍵名是數(shù)字耳舅,但是for...in循環(huán)是以字符串作為鍵名“0”、“1”倚评、“2”等等浦徊。
for...in循環(huán)不僅遍歷數(shù)字鍵名馏予,還會遍歷手動添加的其他鍵,甚至包括原型鏈上的鍵盔性。
某些情況下霞丧,for...in循環(huán)會以任意順序遍歷鍵名。
總之冕香,for...in循環(huán)主要是為遍歷對象而設(shè)計的蛹尝,不適用于遍歷數(shù)組。
for...of循環(huán)相比上面幾種做法悉尾,有一些顯著的優(yōu)點箩言。
for (let value of myArray) {
console.log(value);
}
有著同for...in一樣的簡潔語法,但是沒有for...in那些缺點焕襟。
不同于forEach方法陨收,它可以與break、continue和return配合使用鸵赖。
提供了遍歷所有數(shù)據(jù)結(jié)構(gòu)的統(tǒng)一操作接口务漩。
下面是一個使用 break 語句,跳出for...of循環(huán)的例子它褪。
for (var n of fibonacci) {
if (n > 1000)
break;
console.log(n);
}
上面的例子饵骨,會輸出斐波納契數(shù)列小于等于 1000 的項。如果當(dāng)前項大于 1000茫打,就會使用break語句跳出for...of循環(huán)居触。