forin-forof-forEach有什么不同

1次阅读

共计 976 个字符,预计需要花费 3 分钟才能阅读完成。

30 seconds of code

for…in 用来遍历对象上所有可枚举的 属性

for...in 用来遍历包含在原型链上的对像可枚举属性。可应用于数组、字符串或者对象的遍历上,但不能用于 MapSet

for (let prop in ['a', 'b', 'c']) {console.log(prop); 
  // 0, 1, 2 (数组下标)
}

for (let prop in 'str') {console.log(prop);            
  // 0, 1, 2 (字符串下标)
}

for (let prop in {a: 1, b: 2, c: 3}) {console.log(prop);            
  // a, b, c (对象属性名)
}

for (let prop in new Set(['a', 'b', 'a’])) {console.log(prop);            
  // undefined (no enumerable properties)
}

for…of 用来遍历 iterable 对象的 ,而非属性

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(prop);           
  /* Uncaught TypeError*/
}

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

forEach()遍历数组元素

forEach()是 Array 的原型方法,只用来遍历数组。每次遍历既可以访问到元素,又可以访问 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)
});
'1234'.forEach((val, i) => {console.log(i); 
  // Uncaught TypeError
});

软实力提升

个人公众号

正文完
 0