es6中 for-in for-of的用法和区别

其中for-of是ES6新增的迭代语法

在MDN上的解释:
for...in语句以任意顺序遍历一个对象的可枚举属性。对于每个不同的属性,语句都会被执行。
for...of语句在可迭代对象(包括 Array,Map,Set,String,TypedArray,arguments 对象等等)上创建一个迭代循环,调用自定义迭代钩子,并为每个不同属性的值执行语句

由此概念可看出区别:for..in是返回可枚举对象的属性,而for..of是返回可枚举对象的值
另外一点:for...in会继承, 而for...of不会,

  • for...in实例
Object.prototype.objCustom = function(){}
Array.prototype.arrCustom = function(){}
let iterable = [3,4,5]

iterable.foo = 'hello'
console.log(iterable)

console.log('--------------------')
for(let i in iterable){
    console.log(i)
}

console.log('--------------------')
for(let j in iterable){
    if(iterable.hasOwnProperty(j)){ // hasOwnProperty 判断是自己属性才能输出
	    console.log(j)
    }
}


  • 输出结果
[ 3, 4, 5, foo: 'hello' ]
--------------------
0
1
2
foo
arrCustom
objCustom
--------------------
0
1
2
foo
  • for of
console.log('--------------------')
for(let k of iterable){
    console.log(k)
}

// iterable 百度翻译:可迭代的
--------------------
3
4
5

以上三个结果中:
1 . console.log(iterable) 返回数组本身

2 . 第一个for...in结果看出,可枚举属性除了本身的 0 , 1 , 2 ,foo之外,还有 arrCustom, objCustom。这是由于继承功能, iterable是数组实例,iterable.__proto__指向Array原型对象则有了前面定义的属性arrCustom, 而Array.__proto__指向Object原型对象,则有了前面定义的熟悉objCustom, 原型链在往上Object.__proto__指向null,此时终止继承。

3 . 第二个for...in内部使用hasOwnProperty判断只有是本身的属性才输出

posted @ 2022-08-16 08:40  盘思动  阅读(350)  评论(0编辑  收藏  举报