Symbol.iterator 为每一个对象定义了默认的迭代器。该迭代器可以被 for...of
循环使用。
Symbol.iterator 属性的属性特性: |
|
---|---|
writable | false |
enumerable | false |
configurable | false |
描述
当需要对一个对象进行迭代时(比如开始用于一个for..of
循环中),它的@@iterator
方法都会在不传参情况下被调用,返回的迭代器用于获取要迭代的值。
一些内置类型拥有默认的迭代器行为,其他类型(如 Object
)则没有。下表中的内置类型拥有默认的@@iterator
方法:
Array.prototype[@@iterator]()
TypedArray.prototype[@@iterator]()
String.prototype[@@iterator]()
Map.prototype[@@iterator]()
Set.prototype[@@iterator]()
更多信息请参见迭代协议。
示例
自定义迭代器
我们可以像下面这样创建自定义的迭代器:
var myIterable = {} myIterable[Symbol.iterator] = function* () { yield 1; yield 2; yield 3; }; [...myIterable] // [1, 2, 3]
不符合标准的迭代器
如果一个迭代器 @@iterator
没有返回一个迭代器对象,那么它就是一个不符合标准的迭代器,这样的迭代器将会在运行期抛出异常,甚至非常诡异的 Bug。
var nonWellFormedIterable = {} nonWellFormedIterable[Symbol.iterator] = () => 1 [...nonWellFormedIterable] // TypeError: [] is not a function
规范
Specification | Status | Comment |
---|---|---|
ECMAScript 2015 (6th Edition, ECMA-262) Symbol.iterator |
Standard | Initial definition. |
ECMAScript Latest Draft (ECMA-262) Symbol.iterator |
Draft |
浏览器兼容性
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.
Update compatibility data on GitHub
Desktop | Mobile | Server | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
iterator |
Chrome Full support 43 | Edge Full support 12 | Firefox Full support 36 | IE No support No | Opera Full support 30 | Safari Full support 10 | WebView Android Full support 43 | Chrome Android Full support 43 | Firefox Android Full support 36 | Opera Android Full support Yes | Safari iOS Full support 10 | Samsung Internet Android Full support 4.0 | nodejs Full support 0.12 |
Legend
- Full support
- Full support
- No support
- No support