String.prototype[Symbol.iterator]()

String 值的 [Symbol.iterator]() 方法实现了 可迭代协议,并允许大多数需要可迭代的语法使用字符串,例如 扩展语法for...of 循环。它返回 字符串迭代器对象,该 字符串迭代器对象 产生字符串值的 Unicode 代码点作为单独的字符串。

¥The [Symbol.iterator]() method of String values implements the iterable protocol and allows strings to be consumed by most syntaxes expecting iterables, such as the spread syntax and for...of loops. It returns a string iterator object that yields the Unicode code points of the string value as individual strings.

Try it

语法

¥Syntax

js
string[Symbol.iterator]()

参数

¥Parameters

没有任何。

¥None.

返回值

¥Return value

一个新的 可迭代的迭代器对象,它将字符串值的 Unicode 代码点生成为单独的字符串。

¥A new iterable iterator object that yields the Unicode code points of the string value as individual strings.

描述

¥Description

字符串通过 Unicode 代码点进行迭代。这意味着字素簇将被分割,但代理对将被保留。

¥Strings are iterated by Unicode code points. This means grapheme clusters will be split, but surrogate pairs will be preserved.

js
// "Backhand Index Pointing Right: Dark Skin Tone"
[..."👉🏿"]; // ['👉', '🏿']
// splits into the basic "Backhand Index Pointing Right" emoji and
// the "Dark skin tone" emoji

// "Family: Man, Boy"
[..."👨‍👦"]; // [ '👨', '‍', '👦' ]
// splits into the "Man" and "Boy" emoji, joined by a ZWJ

示例

¥Examples

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

¥Iteration using for...of loop

请注意,你很少需要直接调用此方法。[Symbol.iterator]() 方法的存在使得字符串 iterable,像 for...of 循环这样的迭代语法会自动调用该方法来获取要循环的迭代器。

¥Note that you seldom need to call this method directly. The existence of the [Symbol.iterator]() method makes strings iterable, and iterating syntaxes like the for...of loop automatically call this method to obtain the iterator to loop over.

js
const str = "A\uD835\uDC68B\uD835\uDC69C\uD835\uDC6A";

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

手动滚动迭代器

¥Manually hand-rolling the iterator

你仍然可以手动调用返回的迭代器对象的 next() 方法,以实现对迭代过程的最大控制。

¥You may still manually call the next() method of the returned iterator object to achieve maximum control over the iteration process.

js
const str = "A\uD835\uDC68";

const strIter = str[Symbol.iterator]();

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

规范

Specification
ECMAScript Language Specification
# sec-string.prototype-@@iterator

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看