普通对象添加迭代器

当需要对一个对象进行迭代时(比如用于一个for..of循环中),它的@@iterator方法都会在不传参情况下被调用,返回的迭代器用于获取要迭代的值。

let fridge = { name: "卡萨帝冰箱", color: "白色", brand: "海尔" };
fridge[Symbol.iterator] = function*() {
  yield this.name;
  yield this.color;
  yield this.brand;
};

for(let attr of fridge){
  console.log(attr);
}

let desc = [...fridge];
console.log(desc);

一些内置类型(String、Array、Map、Set)拥有默认的迭代器行为,其他类型(如 Object)则没有。

猜你喜欢

转载自www.cnblogs.com/sea-breeze/p/10849367.html