js中for in, for of 和 forEach區別,你知道嗎?

for...in

說明:For... in 用於遍歷對象的所有可枚舉屬性,包括繼承的可枚舉屬性。 此迭代語句可以用於數組字符串或普通對象,但不能用於 Map 或 Set 對象。

實例:

<code>for (let prop in ['a', 'b', 'c']) {
\tconsole.log(prop);
}
// 0, 1, 2 (array indexes)

for (let prop in 'str') {
\tconsole.log(prop);
}
// 0, 1, 2 (string indexes)

for (let prop in {a: 1, b: 2, c: 3}) {
\tconsole.log(prop);
}
// a, b, c (object property names)

for (let prop in new Set(['a', 'b', 'a', 'd'])) {
\tconsole.log(prop);
}
// undefined (no enumerable properties)/<code>

for...of

說明:For... of 用於迭代可迭代對象,迭代它們的值而不是屬性。 此迭代語句可以用於數組、字符串、 Map 或 Set 對象,但不能用於普通對象。

實例:

<code>for (let val of ['a', 'b', 'c']) 
console.log(val); // a, b, c (array values)

for (let val of 'str')
console.log(val); // s, t, r (string characters)

for (let val of {a: 1, b: 2, c: 3})
console.log(prop); // TypeError (not iterable)

for (let val of new Set(['a', 'b', 'a', 'd']))
console.log(val); // a, b, d (Set values)/<code>

forEach

說明:forEach ()是 Array 原型的一種方法,它允許您迭代數組的元素。 雖然 forEach ()只對數組進行迭代,但是它可以在迭代時同時訪問每個元素的值和索引。

<code>['a', 'b', 'c'].forEach(val => console.log(val));     // a, b, c (array values)

['a', 'b', 'c'].forEach((val, i) => console.log(i)); // 0, 1, 2 (array indexes)
/<code>


分享到:


相關文章: