for..of 和 for..in的区别

适用目标不一样

for..in可用于遍历可枚举数据,如对象、数组、字符串。
什么是可枚举:属性中的enumerable值为true时,就是可枚举的,具体可通过Object.getOwnPropertyDescriptors(o)来查看。

const p = {
  name: "bob",
  age: 18
};

console.log(Object.getOwnPropertyDescriptors(p));
// 输出:
{
  name: {
    value: "bob",
    writable: true,
    enumerable: true,
    configurable: true
  },
  age: { value: 18, writable: true, enumerable: true, configurable: true }
}


const arr = [1, 2, 3, 4];
console.log(Object.getOwnPropertyDescriptors(arr));
输出:
{
  '0': { value: 1, writable: true, enumerable: true, configurable: true },
  '1': { value: 2, writable: true, enumerable: true, configurable: true },
  '2': { value: 3, writable: true, enumerable: true, configurable: true },
  '3': { value: 4, writable: true, enumerable: true, configurable: true },
  length: { value: 4, writable: true, enumerable: false, configurable: false }
}

for..of用于可迭代对象,如:Array, String, Map, Set, 函数的argumentsNodeList
可迭代对象是指具有Symbol.iterator属性的对象,该属性的值为一个函数,返回值是一个迭代器。而迭代器是指具有next方法的对象,该方法返回一个valuedone属性的对象。
在这里插入图片描述

const arr = [1, 2, 3, 4];
const item = arr[Symbol.iterator]();
console.log(item.next());
console.log(item.next());
console.log(item.next());
console.log(item.next());
console.log(item.next());
输出:
{ value: 1, done: false }
{ value: 2, done: false }
{ value: 3, done: false }
{ value: 4, done: false }
{ value: undefined, done: true }

遍历范围不一样

for..in可以遍历原型上的可枚举属性
for..of默认只有遍历自身的属性,具体和迭代器的实现有关。

//默认实现思路
arr[Symbol.iterator] = function () {
  const _this = this;
  return {
    i: 0,
    next() {
      return this.i < _this.length ? { value: _this[this.i++], done: false } : { value: undefined, done: true };
    }
  };
};

//通过自定义迭代器改变输出值
Array.prototype.foo = "aaaaa";
const arr = [1, 2, 3, 4];
arr[Symbol.iterator] = function () {
  const _this = this;
  //手动修改迭代器的实现方法
  Object.keys(this.__proto__).forEach((item) => this.push(this.__proto__[item]));
  return {
    i: 0,
    next() {
      return this.i < _this.length ? { value: _this[this.i++], done: false } : { value: undefined, done: true };
    }
  };
};

for (const value of arr) {
  console.log(value);
}

//输出:
1
2
3
4
aaaaa

输出结果不一样

for..in遍历得到的key,且不保证顺序
for..of遍历默认得到的是value,具体和迭代器实现有关
根据上述代码修改

const arr = [3, 5, 6, 8];
arr[Symbol.iterator] = function () {
  const _this = this;
  return {
    i: 0,
    next() {
      // return this.i < _this.length ? { value: _this[this.i++], done: false } : { value: undefined, done: true };
      return this.i < _this.length ? { value: this.i++, done: false } : { value: undefined, done: true };
    }
  };
};

for (const value of arr) {
  console.log(value);
}

输出:
0
1
2
3
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值