【快速入门系列】简述 for...in 和 for...of 区别

引言

在对数组或对象进行遍历时,咱们常常会使用到两种方法:for...infor...of,那么这两种方法之间的区别是什么呢?让咱们来研究研究。数组

1、for...in

首先咱们看下MDN对for...in方法的解释:for...in | MDN函数

for...in 循环只遍历可枚举属性。像 Array和 Object使用内置构造函数所建立的对象都会继承自Object.prototype和String.prototype的不可枚举属性,例如 String 的 indexOf() 方法或 Object的toString()方法。循环将遍历对象自己的全部可枚举属性,以及对象从其构造函数原型中继承的属性(更接近原型链中对象的属性覆盖原型属性)。

首先,咱们简单的使用for...in分别对对象和数组进行遍历:测试

// 遍历对象
let obj = {
  a: 1,
  b: 2,
  c: 3
};
for(let item in obj) {
  console.log("item:" + item);
  console.log(obj[item]);
}

// 运行结果
item:a
1
item:b
2
item:c
3
// 遍历数组
let arr = [1, 2, 3];
for(let item in arr) {
  console.log("item:" + item);
  console.log(arr[item]);
}

// 运行结果
item:0
1
item:1
2
item:2
3

咱们发现,使用for...in进行遍历时,item值为对象的key,为数组的index。
咱们知道,数组索引只是具备整数名称的枚举属性,而且与通用对象属性相同,所以不能保证for...in以某种固定的顺序返回索引,所以,不推荐使用for...in进行数组的遍历prototype

下面,咱们在上面代码的基础上,在arr数组上增长一个自定义属性,再次遍历,查看结果。code

arr.name = 'arrName';
for(let item in arr) {
  console.log("item:" + item);
  console.log(arr[item]);
}

// 运行结果
item:0
1
item:1
2
item:2
3
item:name
arrName

咱们发现,for...in不只会遍历数组中的元素,还会遍历自定义属性对象

2、for...of

说完for...in咱们再来看看for...of,咱们仍是先来看看MDN对其的解释 for...of | MDN继承

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

一样的,咱们仍是使用与for...in相同的代码进行测试索引

// 遍历对象
let obj = {
  a: 1,
  b: 2,
  c: 3
};
for(let item of obj) {
  console.log("item:" + item);
  console.log(obj[item]);
}

// 运行结果
for(let item of obj) {
                ^

TypeError: obj is not iterable
...
// 遍历数组
let arr = [1, 2, 3];
for(let item of arr) {
  console.log("item:" + item);
  console.log(arr[item]);
}

// 运行结果
item:1
undefined
item:2
undefined
item:3
undefined

咱们能够看出,使用for...of对对象进行遍历时,报了TypeError: obj is not iterable错误,对数组进行遍历时,item直接是数组每一项的值ip

咱们再为arr增长自定义属性,查看效果。原型链

arr.name = 'arrName';
for(let item in arr) {
  console.log("item:" + item);
  console.log(arr[item]);
}

// 运行结果
item:1
undefined
item:2
undefined
item:3
undefined

for...of没有对数组的自定义属性进行遍历

3、总结

根据以上测试结果并参考了相关资料,咱们得出了如下结论:

  1. 遍历对象时推荐使用for...in,其中item为对象的key。使用for...of会报错。
  2. 遍历数组时推荐使用for...of,其中item为数组每一项的值。使用for...in则不能保证遍历顺序且会遍历出自定义属性。
  3. for...in是ES5特性,for...of是ES6特性,所以须要注意兼容性。
  4. 若是要使用for...of遍历普通对象,须要配合Object.keys()一块儿使用。

结束语

以上内容是咱们对for...infor...of的测试对比,在使用时记住其区别可更快的编写代码和排查错误,若想了解其更深层区别,建议认真阅读MDN相关资料。

相关文章
相关标签/搜索