for-in 和 for-of 的区别
2025/3/6大约 1 分钟
循环数组用
for...of,循环对象用for...in
for...in
遍历的结果是数组元素的下标
遍历对象的可枚举属性,以及对象从构造函数原型中继承的属性,对于每个不同的属性,语句都会被执行,可以用
hasOwnProperty()去掉非自身属性
不建议使用
for...in遍历数组,因为输出的顺序是不固定的
如果迭代的对象的变量值是
null或者undefined,for...in不报错,也不执行循环体,建议在使用 for in 循环之前,先检查该对象的值是不是null或者undefined
for...of
ES6 新语法
遍历的结果是元素的值
在可迭代对象(包括
Array、String、Map、Set、arguments等等)上创建了一个循环,调用自定义迭代钩子,并为每个不同属性的值执行语句
如果迭代的对象的变量值是
null或者undefined,Object等等,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
}