lxq.link
postscategoriestoolsabout

JS 的 for-in 和 for-of 循环

for-in,es5标准,常用来遍历对象,也可以遍历数组。当用for-in 遍历数组的时候,和 for 循环的区别是 for-in 会遍历数组的可枚举属性,并且定义的索引是字符串类型的。

for-of,es6标准,在可迭代对象(包括 Array,Map,Set,String,TypedArray,arguments 对象等等)上创建一个迭代循环,调用自定义迭代钩子,并为每个不同属性的值执行语句 (MDN)。

let arr = ["a", "b", "c"];
arr.k = "v";

Array.prototype.arrCustom = "ac";
Object.prototype.objCustom = "oc";

for(let i = 0; i < arr.length; i++){
  console.log(i, Object.prototype.toString.call(i), arr[i]) 
}
// 输出:
// 0 "[object Number]" "a"
// 1 "[object Number]" "b"
// 2 "[object Number]" "c"

for(let i in arr){
  console.log(i, Object.prototype.toString.call(i), arr[i])
}
// 输出:
// 0 [object String] a
// 1 [object String] b
// 2 [object String] c
// k [object String] v
// arrCustom [object String] ac
// objCustom [object String] oc

// 使用 hasOwnProperty 来过滤只属于自身的枚举属性,而不是继承的
for(let i in arr){
  if(arr.hasOwnProperty(i)){
    console.log(i, Object.prototype.toString.call(i), arr[i])
  }
}
// 输出:
// 0 [object String] a
// 1 [object String] b
// 2 [object String] c
// k [object String] v
 
for(k of arr){
  console.log(k);
}
// 输出:
// a
// b
// c
2019-08-29