<pre>
1.for...of循環(huán)可以代替數(shù)組實例的forEach方法:
const arr = ['red', 'green', 'blue'];
arr.forEach(function (element, index) {
console.log(element); // red green blue
console.log(index); // 0 1 2
});
for(let i of arr){
console.log(i); // red green blue
}
2.JavaScript原有的for...in循環(huán),只能獲得對象的鍵名,不能直接獲取鍵值。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
}
3.for...of循環(huán)調(diào)用遍歷器接口,數(shù)組的遍歷器接口只返回具有數(shù)字索引的屬性。這一點(diǎn)跟for...in循環(huán)也不一樣:
let arr = [3,5,7];
arr.hello = 'hello';
for(let i in arr){
console.log(i); // "0","1","2","3"
}
for(let i of arr){
console.log(i); // "3","5","7"
}
</pre>