JavaScript中for...in、 for...of 、 forEach循环的区别

234 阅读1分钟

for...in用于遍历对象的所有可枚举的属性,包括继承的属性。可以操作数组、字符串、对象,但是Map、Set无效。

    for (let prop in ['a', 'b', 'c']) 
      console.log(prop);            // 0, 1, 2 (array indexes)
   
    for (let prop in 'str') 
      console.log(prop);            // 0, 1, 2 (string indexes)
    
    for (let prop in {a: 1, b: 2, c: 3}) 
      console.log(prop);            // a, b, c (object property names)
    
    for (let prop in new Set(['a', 'b', 'a', 'd'])) 
      console.log(prop);            // undefined (no enumerable properties)

for...of 用于遍历可迭代的对象, 遍历是值而不是属性,可用于数组、字符串、Map、Set,但不能用于对象。

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(val);           // TypeError (is not iterable)

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

forEach() 是数组原型的方法,用于迭代数组的元素,遍历数组接受两个参数:索引(index)、数组当前项。

['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)
);

原文