当需要对一个对象进行迭代时(比如用于一个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
)则没有。