與Array
一起使用時拢驾,for...of
循環(huán)和for...in
循環(huán)之間的區(qū)別
Object.prototype.objCustom = function() {};
Array.prototype.arrCustom = function() {};
let iterable = [3, 5, 7];
iterable.foo = 'hello';
for (let i in iterable) {
console.log(i); // 0, 1, 2, "foo", "arrCustom", "objCustom"
}
for (let i in iterable) {
if (iterable.hasOwnProperty(i)) {
console.log(i); // 0, 1, 2, "foo"
}
}
for (let i of iterable) {
console.log(i); // 3, 5, 7
}
無論是for...in還是for...of語句都是迭代一些東西。它們之間的主要區(qū)別在于它們的迭代方式驶悟。
for...in
語句以任意順序迭代對象的可枚舉屬性夏醉。
每個對象將繼承objCustom
屬性嫁赏,并且作為Array
的每個對象將繼承arrCustom
屬性,因為將這些屬性添加到Object.prototype
和Array.prototype
。由于繼承和原型鏈茵汰,對象iterable
繼承屬性objCustom
和arrCustom
赂弓。
此循環(huán)僅以原始插入順序記錄iterable
對象的可枚舉屬性绑榴。它不記錄數(shù)組元素 3
, 5
, 7
或hello
,因為這些不是枚舉屬性盈魁。但是它記錄了數(shù)組索引以及arrCustom
和objCustom
翔怎。
for...of
語句遍歷可迭代對象定義要迭代的數(shù)據(jù)。
該循環(huán)迭代并記錄iterable
作為可迭代對象定義的迭代值,這些是數(shù)組元素 3
, 5
, 7
赤套,而不是任何對象的屬性飘痛。