String.prototype[Symbol.iterator]()

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 2015 年 9 月以來,該特性已在各大瀏覽器中可用。

String 物件的 [Symbol.iterator]() 方法實現了 iterable protocol,它允許字串被大多數期望 iterable 的語法所使用,例如 spread 語法for...of 迴圈。它返回一個 string iterator object,該物件會逐個產生字串中的 Unicode code point。

試一試

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]()

引數

無。

返回值

一個實現 iterable iterator object 的新物件,它會逐個產生字串中的 Unicode code point。

描述

字串是按 Unicode code point 進行迭代的。這意味著字形簇(grapheme clusters)會被拆分,但代理對(surrogate pairs)會被保留。

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]() 方法的存在使得字串成為 iterable,像 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"

規範

規範
ECMAScript® 2026 語言規範
# sec-string.prototype-%symbol.iterator%

瀏覽器相容性

另見