The well-known Symbol.iterator symbol specifies the default iterator for an object. Used by for...of .

The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.

描述

Whenever an object needs to be iterated (such as at the beginning of a for..of loop), its @@iterator method is called with no arguments, and the returned iterator is used to obtain the values to be iterated.

Some built-in types have a default iteration behavior, while other types (such as Object ) do not. The built-in types with a @@iterator method are:

另请参阅 Iteration protocols 了解更多信息。

特性属性在 Symbol.iterator
可写 no
可枚举 no
可配置 no

范例

User-defined iterables

We can make our own iterables like this:

var 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';
  }
}
[...new Foo] // [ 1, 2, 3 ]
[...someObj] // [ 'a', 'b' ]
					

Non-well-formed iterables

If an iterable's @@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:

var nonWellFormedIterable = {}
nonWellFormedIterable[Symbol.iterator] = () => 1
[...nonWellFormedIterable] // TypeError: [] is not a function
					

规范

规范
ECMAScript (ECMA-262)
The definition of 'Symbol.iterator' in that specification.

浏览器兼容性

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. 更新 GitHub 上的兼容性数据
Desktop Mobile Server
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet Node.js
iterator Chrome 43 Edge 12 Firefox 36 IE No Opera 30 Safari 10 WebView Android 43 Chrome Android 43 Firefox Android 36 Opera Android 30 Safari iOS 10 Samsung Internet Android 4.0 nodejs 0.12

图例

完整支持

完整支持

不支持

不支持

另请参阅

元数据

  • 最后修改: