跳至主要內容

for-in 和 for-of 的区别

Yang大约 1 分钟JavaScript

循环数组用 for...of,循环对象用 for...in

for...inopen in new window

遍历的结果是数组元素的下标

遍历对象的可枚举属性,以及对象从构造函数原型中继承的属性,对于每个不同的属性,语句都会被执行,可以用 hasOwnProperty() 去掉非自身属性

不建议使用 for...in 遍历数组,因为输出的顺序是不固定的

如果迭代的对象的变量值是 null 或者 undefinedfor...in 不报错,也不执行循环体,建议在使用 for in 循环之前,先检查该对象的值是不是 null 或者 undefined

for...ofopen in new window

ES6 新语法

遍历的结果是元素的值

在可迭代对象(包括 ArrayStringMapSetarguments 等等)上创建了一个循环,调用自定义迭代钩子,并为每个不同属性的值执行语句

如果迭代的对象的变量值是 null 或者 undefinedObject 等等, for...of 会直接报错

区别

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 in iterable) {
  if (iterable.hasOwnProperty(i)) {
    console.log(i) // 0, 1, 2, "foo"
  }
}

for (let i of iterable) {
  console.log(i) // 3, 5, 7
}
上次编辑于:
贡献者: sunzhenyang