Iterator.prototype[Symbol.iterator]()
Iterator
实例的 [Symbol.iterator]()
方法实现了 可迭代协议,并允许大多数需要迭代的语法使用内置迭代器,例如 扩展语法 和 for...of
循环。它返回 this
的值,即迭代器对象本身。
¥The [Symbol.iterator]()
method of Iterator
instances implements the iterable protocol and allows built-in iterators to be consumed by most syntaxes expecting iterables, such as the spread syntax and for...of
loops. It returns the value of this
, which is the iterator object itself.
语法
参数
返回值
示例
使用 for...of 循环进行迭代
¥Iteration using for...of loop
请注意,你很少需要直接调用此方法。[Symbol.iterator]()
方法的存在使得内置迭代器 iterable,像 for...of
循环这样的迭代语法会自动调用该方法来获取要循环的迭代器。
¥Note that you seldom need to call this method directly. The existence of the [Symbol.iterator]()
method makes built-in iterators iterable, and iterating syntaxes like the for...of
loop automatically call this method to obtain the iterator to loop over.
const arrIterator = [1, 2, 3].values();
for (const value of arrIterator) {
console.log(value);
}
// Logs: 1, 2, 3
规范
Specification |
---|
ECMAScript Language Specification # sec-%iteratorprototype%-@@iterator |
浏览器兼容性
BCD tables only load in the browser
也可以看看
¥See also