Array.prototype[@@iterator]()

@@iterator 属性和 Array.prototype.values() 属性的初始值是同一个函数对象。

语法

arr[Symbol.iterator]()

返回值

数组的 iterator 方法,默认情况下,与 values() 返回值相同, arr[Symbol.iterator] 则会返回 values() 函数。

示例

使用 for...of 循环进行迭代

var arr = ['a', 'b', 'c', 'd', 'e'];
var eArr = arr[Symbol.iterator]();
var eArr = arr[Symbol.iterator]();
// 浏览器必须支持 for...of 循环
for (let letter of eArr) {
  console.log(letter);
}

另一种迭代方式

var arr = ['a', 'b', 'c', 'd', 'e'];
var eArr = arr[Symbol.iterator]();
console.log(eArr.next().value); // a
console.log(eArr.next().value); // b
console.log(eArr.next().value); // c
console.log(eArr.next().value); // d
console.log(eArr.next().value); // e

Use Case for brace notation

The use case for this syntax over using the dot notation (Array.prototype.values()) is in a case where you don't know what object is going to be ahead of time. If you have a function that takes an iterator and then iterate over the value, but don't know if that Object is going to have a [Iterable].prototype.values method. This could be a built-in object like String object or a custom object.

function logIterable(it) {
  var iterator = it[Symbol.iterator]();
  // 浏览器必须支持 for...of 循环
  for (let letter of iterator) {
      console.log(letter);
  }
}

// Array
logIterable(['a', 'b', 'c']);
// a
// b
// c

// string
logIterable('abc'); 
// a
// b
// c

规范

规范名称 规范状态 备注
ECMAScript 2015 (6th Edition, ECMA-262)
Array.prototype[@@iterator]()
Standard 首次定义
ECMAScript Latest Draft (ECMA-262)
Array.prototype[@@iterator]()
Draft

浏览器兼容性

Update compatibility data on GitHub
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung InternetNode.js
@@iteratorChrome Full support 38Edge Full support 12Firefox Full support 36
Full support 36
No support 27 — 36
Notes Alternate Name
Notes A placeholder property named @@iterator is used.
Alternate Name Uses the non-standard name: @@iterator
No support 17 — 27
Notes Alternate Name
Notes A placeholder property named iterator is used.
Alternate Name Uses the non-standard name: iterator
IE No support NoOpera Full support 25Safari Full support YesWebView Android Full support YesChrome Android Full support 38Firefox Android Full support 36
Full support 36
No support 27 — 36
Notes Alternate Name
Notes A placeholder property named @@iterator is used.
Alternate Name Uses the non-standard name: @@iterator
No support 17 — 27
Notes Alternate Name
Notes A placeholder property named iterator is used.
Alternate Name Uses the non-standard name: iterator
Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yesnodejs Full support 0.12

Legend

Full support  
Full support
No support  
No support
See implementation notes.
See implementation notes.
Uses a non-standard name.
Uses a non-standard name.

参见