for...of與for...in的區別
阿新 • • 發佈:2021-08-04
轉載:for...of
與for...in
的區別
無論是for...in
還是for...of
語句都是迭代一些東西。它們之間的主要區別在於它們的迭代方式。
for...in
語句以任意順序迭代物件的可列舉屬性。
for...of
語句遍歷可迭代物件定義要迭代的資料。
以下示例顯示了與Array
一起使用時,for...of
迴圈和for...in
迴圈之間的區別。
Object.prototype.objCustom = function() {}; Array.prototype.arrCustom = function() {}; let iterable = [3, 5, 7]; iterable.foo= 'hello'; for (let i in iterable) { console.log(i); // logs 0, 1, 2, "foo", "arrCustom", "objCustom" } for (let i in iterable) { if (iterable.hasOwnProperty(i)) { console.log(i); // logs 0, 1, 2, "foo" } } for (let i of iterable) { console.log(i); // logs 3, 5, 7 }
Object.prototype.objCustom = function() {}; Array.prototype.arrCustom = function() {}; let iterable = [3, 5, 7]; iterable.foo = 'hello';
每個物件將繼承objCustom
屬性,並且作為Array
的每個物件將繼承arrCustom
屬性,因為將這些屬性新增到Object.prototype
(en-US)和Array.prototype
。由於繼承和原型鏈,物件iterable
繼承屬性objCustom
和arrCustom
。
for (let i in iterable) { console.log(i); // logs 0, 1, 2, "foo", "arrCustom", "objCustom"}
此迴圈僅以原始插入順序記錄iterable
物件的可列舉屬性。它不記錄陣列元素3
,5
,7
或hello
,因為這些不是列舉屬性。但是它記錄了陣列索引以及arrCustom
和objCustom
。如果你不知道為什麼這些屬性被迭代,array iteration and for...in
中有更多解釋。
for (let i in iterable) { if (iterable.hasOwnProperty(i)) { console.log(i); // logs 0, 1, 2, "foo" } }
這個迴圈類似於第一個,但是它使用hasOwnProperty()
來檢查,如果找到的列舉屬性是物件自己的(不是繼承的)。如果是,該屬性被記錄。記錄的屬性是0
,1
,2
和foo
,因為它們是自身的屬性(不是繼承的)。屬性arrCustom
和objCustom
不會被記錄,因為它們是繼承的。
for (let i of iterable) { console.log(i); // logs 3, 5, 7 }
該迴圈迭代並記錄iterable
作為可迭代物件定義的迭代值,這些是陣列元素3
,5
,7
,而不是任何物件的屬性。