Symbol.iterator
Symbol.iterator
静态数据属性代表 众所周知的符号 Symbol.iterator
。可迭代协议 查找此符号以查找返回对象迭代器的方法。为了使对象可迭代,它必须具有 [Symbol.iterator]
键。
¥The Symbol.iterator
static data property represents the well-known symbol Symbol.iterator
. The iterable protocol looks up this symbol for the method that returns the iterator for an object. In order for an object to be iterable, it must have an [Symbol.iterator]
key.
Try it
值
描述
¥Description
每当一个对象需要迭代时(例如在 for...of
循环开始时),就会不带参数地调用其 [Symbol.iterator]()
方法,并使用返回的迭代器来获取要迭代的值。
¥Whenever an object needs to be iterated (such as at the beginning of a for...of
loop), its [Symbol.iterator]()
method is called with no arguments, and the returned iterator is used to obtain the values to be iterated.
某些内置类型具有默认迭代行为,而其他类型(例如 Object
)则没有。一些具有 [Symbol.iterator]()
方法的内置类型是:
¥Some built-in types have a default iteration behavior, while other types (such as Object
) do not. Some built-in types with a [Symbol.iterator]()
method are:
Array.prototype[Symbol.iterator]()
TypedArray.prototype[Symbol.iterator]()
String.prototype[Symbol.iterator]()
Map.prototype[Symbol.iterator]()
Set.prototype[Symbol.iterator]()
另请参阅 迭代协议 了解更多信息。
¥See also Iteration protocols for more information.
示例
用户定义的迭代
¥User-defined iterables
我们可以像这样创建自己的迭代:
¥We can make our own iterables like this:
const myIterable = {};
myIterable[Symbol.iterator] = function* () {
yield 1;
yield 2;
yield 3;
};
[...myIterable]; // [1, 2, 3]
或者可以使用 计算属性 直接在类或对象内部定义迭代:
¥Or iterables can be defined directly inside a class or object using a computed property:
class Foo {
*[Symbol.iterator]() {
yield 1;
yield 2;
yield 3;
}
}
const someObj = {
*[Symbol.iterator]() {
yield "a";
yield "b";
},
};
console.log(...new Foo()); // 1, 2, 3
console.log(...someObj); // 'a', 'b'
非格式良好的迭代
¥Non-well-formed iterables
如果可迭代对象的 [Symbol.iterator]()
方法不返回迭代器对象,则它是非格式良好的可迭代对象。像这样使用它可能会导致运行时异常或错误行为:
¥If an iterable's [Symbol.iterator]()
method does not return an iterator object, then it is a non-well-formed iterable. Using it as such is likely to result in runtime exceptions or buggy behavior:
const nonWellFormedIterable = {};
nonWellFormedIterable[Symbol.iterator] = () => 1;
[...nonWellFormedIterable]; // TypeError: [Symbol.iterator]() returned a non-object value
规范
Specification |
---|
ECMAScript Language Specification # sec-symbol.iterator |
浏览器兼容性
BCD tables only load in the browser