for...of loop和 for...in loop的差異?

for...of loop:

create a loop iterating over "iterable objects"(像是: Array/ Map/ Set/ String/ TypedArray/ arguments object, etc.), 會將物件的屬性值取出。

但for...in loop是將物件的屬性取出。



以下從這篇連結擷取出它們兩者的不同:

https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Statements/for...of


Difference between for...of and for...in

The for...in loop will iterate over all enumerable properties of an object.

The for...of syntax is specific to collections, rather than all objects. It will iterate in this manner over the elements of any collection that has a [Symbol.iterator] property.


e.g.

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 of iterable) {

  console.log(i);                                             // 3, 5, 7 --> 因collection只限於指[3, 5, 7]

}

留言

熱門文章