1、for of
const arr = ['red', 'green', 'blue']; for(let v of arr) { console.log(v); // red green blue
}
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
循環,允許遍歷獲得鍵值。
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...in
循環讀取鍵名,for...of
循環讀取鍵值。如果要通過for...of
循環,獲取數組的索引,可以借助數組實例的entries
方法和keys
方法.
for of:不同於forEach
方法,它可以與break
、continue
和return
配合使用。
2、for in的缺陷
for in會遍歷出原型對象以及對象本身屬性值。
Object.prototype.objCustom = function() {}; Array.prototype.arrCustom = function() {}; var arr = [3, 5, 7]; arr.foo = 'hello'; for (var i in arr) { console.log(i); } // 結果是: // 0 // 1 // 2 // foo // arrCustom // objCustom
Object.prototype.objCustom = function() {}; Array.prototype.arrCustom = function() {}; var arr = [3, 5, 7]; arr.foo = 'hello'; for (var i in arr) { if (arr.hasOwnProperty(i)) { console.log(i); } } // 結果是: // 0 // 1 // 2 // foo
3、foreach的缺陷
遍歷數組時 無法break或者return false
var arr = [3, 5, 7]; arr.forEach(function (value) { console.log(value); if (value == 5) { return false; } }); // 結果是: // 3 // 5 // 7