String.prototype[Symbol.iterator]()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

String 值的 [Symbol.iterator]() 方法实现了可迭代协议,并允许字符串与大多数期望传入可迭代对象的语法一起使用,例如展开语法for...of 循环。它返回一个字符串迭代器对象,它按 Unicode 码位迭代字符串值并以字符串的形式返回。

尝试一下

const str = "The quick red fox jumped over the lazy dog's back.";

const iterator = str[Symbol.iterator]();
let theChar = iterator.next();

while (!theChar.done && theChar.value !== " ") {
  console.log(theChar.value);
  theChar = iterator.next();
  // Expected output: "T"
  //                  "h"
  //                  "e"
}

语法

js
string[Symbol.iterator]()

返回值

一个新的可迭代迭代器对象,它以字符串值中的 Unicode 码位生成单独的字符串。

描述

按 Unicode 码位迭代字符串。这意味着会将字素簇拆分,但代理对将被保留。

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

示例

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

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

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"

手动迭代

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

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® 2025 Language Specification
# sec-string.prototype-%symbol.iterator%

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobileserver
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
Deno
Node.js
[Symbol.iterator]

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
Uses a non-standard name.
Has more compatibility info.

参见