Symbol.iterator 是内置符号,用于定义对象的默认迭代行为。通过实现 [Symbol.iterator]() 方法并返回符合迭代器协议的对象(具有 next() 方法,返回 {value, done}),可使对象支持 for...of、扩展运算符等语法。常用生成器函数简化实现,如 [Symbol.iterator]() { yield* iterable; }。该方法让类数组或自定义结构能被原生迭代操作使用。
JavaScript中的Symbol.iteratorfor...of...Symbol.iteratornext(){ value: any, done: boolean }[Symbol.iterator]()const myCollection = {
items: ['a', 'b', 'c'],
[Symbol.iterator]() {
let index = 0;
return {
next: () => {
if (index < this.items.length) {
return { value: this.items[index++], done: false };
} else {
return { done: true };
}
}
};
}
};
// 现在可以使用 for...of
for (const item of myCollection) {
console.log(item); // 输出: a, b, c
}
// 也可以使用扩展运算符
console.log([...myCollection]); // ['a', 'b', 'c']
function*const counter = {
from: 1,
to: 5,
*[Symbol.iterator]() {
for (let i = this.from; i <= this.to; i++) {
yield i;
}
}
};
for (const num of counter) {
console.log(num); // 输出: 1, 2, 3, 4, 5
}
next()Symbol.iteratorfor...of...const [a, b] = iterable;Array.from()new Set(iterable)new Map(iterable)Symbol.iteratorSymbol.iterator