javaScript中 for...in 和 for...of 的區別

for...in和for...of使用場景差別

  • 一句話:遍歷對象的屬性時,用for...in。想遍歷數組中元素的值的話,用for...of

for...in 和 for...of的差別解析

  • for...in ES5 標準,for...of ES6 針對for...in的不足而補充的方法。
  • for...in遍歷的是 '鍵名'。for...of遍歷的是數組中元素的值。
  • 當使用for...in遍歷數組的時候,咱們獲得的其實是數組的索引值(鍵值),同時若是數組存在別的屬性的話,也會被遍歷出來。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); //  0, 1, 2, "foo", "arrCustom", "objCustom"
}


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

參考

  1. 簡述js中 for in 與 for of 區別
相關文章
相關標籤/搜索