1. 程式人生 > 其它 >for...of與for...in的區別

for...of與for...in的區別

轉載:for...offor...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繼承屬性objCustomarrCustom

for (let i in iterable) {
  console.log(i); // logs 0, 1, 2, "foo", "arrCustom", "objCustom"
}

此迴圈僅以原始插入順序記錄iterable物件的可列舉屬性。它不記錄陣列元素3,5,7hello,因為這些不是列舉屬性。但是它記錄了陣列索引以及arrCustomobjCustom。如果你不知道為什麼這些屬性被迭代,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,2foo,因為它們是自身的屬性(不是繼承的)。屬性arrCustomobjCustom不會被記錄,因為它們是繼承的

for (let i of iterable) {
  console.log(i); // logs 3, 5, 7
}

該迴圈迭代並記錄iterable作為可迭代物件定義的迭代值,這些是陣列元素3,5,7,而不是任何物件的屬性