String.prototype[@@iterator]()

[@@iterator]() 方法返回一个新的Iterator对象,它遍历字符串的代码点,返回每一个代码点的字符串值。

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.

语法

string[Symbol.iterator]

返回值

一个新的Iterator对象。

示例

使用[@@iterator]()

var string = 'A\uD835\uDC68';

var strIter = string[Symbol.iterator]();

console.log(strIter.next().value); // "A"
console.log(strIter.next().value); // "\uD835\uDC68"

通过 for..of 使用[@@iterator]()

var string = 'A\uD835\uDC68B\uD835\uDC69C\uD835\uDC6A';

for (var v of string) {
  console.log(v);
}
// "A"
// "\uD835\uDC68"
// "B"
// "\uD835\uDC69"
// "C"
// "\uD835\uDC6A"

规范

Specification Status Comment
ECMAScript 2015 (6th Edition, ECMA-262)
String.prototype[@@iterator]()
Standard Initial definition.
ECMAScript Latest Draft (ECMA-262)
String.prototype[@@iterator]()
Draft

浏览器兼容性

We're converting our compatibility data into a machine-readable JSON format. This compatibility table still uses the old format, because we haven't yet converted the data it contains. Find out how you can help!
Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
基本支持 (Yes) 36 (36) [1] 未实现 未实现 未实现
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
基本支持 未实现 (Yes) 36.0 (36) [1] 未实现 未实现 未实现

[1] From Gecko 17 (Firefox 17 / Thunderbird 17 / SeaMonkey 2.14) to Gecko 26 (Firefox 26 / Thunderbird 26 / SeaMonkey 2.23 / Firefox OS 1.2) the iterator property was used (bug 907077), and from Gecko 27 to Gecko 35 the "@@iterator" placeholder was used. In Gecko 36 (Firefox 36 / Thunderbird 36 / SeaMonkey 2.33), the @@iterator symbol got implemented (bug 918828).

相关链接