JS for-in和for-of的区别

JS for-in和for-of的区别

for-in

let arr = [1, 2, 3, 4, 5];

Array.prototype.id = 123;
arr.name = 'zk';

for(let index in arr)
{
    console.log(arr[index]);
    // output:  1 2 3 4 5 zk 123
}

for-of

let arr = [1, 2, 3, 4, 5];

Array.prototype.id = 123;
arr.name = 'zk';

for(let value of arr)
{
    console.log(value);
    // output:  1 2 3 4 5
}

区别

  • for-in只是获取数组的索引;而for-of会获取数组的值
  • for-in会遍历对象的整个原型链,性能差;而for-of只遍历当前对象,不会遍历原型链
  • 对于数组的遍历,for-in会返回数组中所有可枚举的属性(包括原型链上可枚举的属性);for-of只返回数组的下标对应的属性值
  • for-of适用遍历数组/字符串/map/set等有迭代器对象的集合,但是不能遍历普通对象(obj is not iterable)

补充说明for-of只遍历当前有迭代器对象的集合,不会遍历原型链:

let obj = {
    name: 'zk',
    sex: 'male'
}

console.log(Object.keys(obj));
//output: ['name', 'sex']

obj.dance = function(){
    console.log('dance');
}

Object.prototype.say = function(){
    console.log('say');
}

for(let value of Object.keys(obj))
{
    console.log(value);
    //output: name, sex, dance
}
posted @ 2022-08-11 10:15  zakun  阅读(80)  评论(0编辑  收藏  举报
返回顶部