javascript中for...in和for...of的区别

for...of循环是ES6引入的新的语法。

for...in遍历拿到的x是键(下标)。而for...of遍历拿到的x是值,但在对象中会提示不是一个迭代器报错。例子如下:

let x;
let a = ['A','B','C'];
let b = {name: '刘德华',age: '18'};

console.log(a.length);
for(x of a){
  console.log(x); //A,B,C
}
for(x in a){
  console.log(x+':'+a[x]); //0:A,1:B,2:C
}
/*for(x of b){
  console.log(x); //报错
}*/
for(x in b){
  console.log(x); //name,age
}

for...in由于历史遗留问题,它遍历的实际上是对象的属性名称,一个Array数据也是一个对象,数组中的每个元素的索引被视为属性名称。

所以我们可以看到使用for...in循环Array数组时,拿到的其实是每个元素的索引。如下,把name包括在内,但是Array的length属性却不包括在内,for...of循环则完全修复了这些问题,它只循环集合本身的元素

a.name = "Hello";
for(x in a){
  console.log(x); //0,1,2,name
}

console.log(a.length); //3

原文地址:https://www.cnblogs.com/jinbang/p/6847365.html