Array.prototype.toLocaleString()
toLocaleString() 方法是 Array 例項的一個方法,它返回一個表示陣列元素的字串。元素使用它們的 toLocaleString 方法轉換為字串,這些字串由一個特定於區域設定的字串(例如逗號 ",")分隔。
試一試
const array = [1, "a", new Date("21 Dec 1997 14:12:00 UTC")];
const localeString = array.toLocaleString("en", { timeZone: "UTC" });
console.log(localeString);
// Expected output: "1,a,12/21/1997, 2:12:00 PM",
// This assumes "en" locale and UTC timezone - your results may vary
語法
toLocaleString()
toLocaleString(locales)
toLocaleString(locales, options)
引數
locales可選-
一個帶有 BCP 47 語言標籤的字串,或者此類字串的陣列。關於
locales引數的一般形式和解釋,請參閱Intl主頁上的引數說明。 options可選-
一個帶有配置屬性的物件。這裡可以傳遞的內容取決於正在轉換的元素。例如,對於數字,請參閱
Number.prototype.toLocaleString()。
返回值
一個表示陣列元素的字串。
描述
Array.prototype.toLocaleString 方法會遍歷其內容,使用提供的 locales 和 options 引數呼叫每個元素的 toLocaleString 方法,並將它們連線起來,分隔符由實現定義(例如逗號 ",")。
注意: locales 或 options 引數不控制陣列元素之間的分隔符;它們只是被傳遞給每個元素的 toLocaleString() 方法。實際的分隔符(通常是逗號)僅取決於主機當前的區域設定。如果您期望本地化的列表格式,請考慮使用 Intl.ListFormat。
如果元素是 undefined 或 null,它將被轉換為一個空字串,而不是字串 "null" 或 "undefined"。
當用於 稀疏陣列時,toLocaleString() 方法會將空槽視為具有 undefined 值進行迭代。
toLocaleString() 方法是 通用的。它只期望 this 值具有 length 屬性和整數鍵屬性。
示例
使用區域設定和選項
陣列的元素使用它們的 toLocaleString 方法轉換為字串。例如,這個片段會隱式呼叫 Number.prototype.toLocaleString() 方法來顯示 prices 陣列中字串和數字的貨幣。
const prices = ["¥7", 500, 8123, 12];
prices.toLocaleString("ja-JP", { style: "currency", currency: "JPY" });
// "¥7,¥500,¥8,123,¥12"
列表分隔符
列表分隔符不受 locales 引數的影響。要配置它,請改用 Intl.ListFormat。
const nums = [8888, 9999];
console.log(nums.toLocaleString("zh")); // "8,888,9,999"
const formatter = new Intl.ListFormat("zh", {
type: "conjunction",
style: "narrow",
});
console.log(formatter.format(nums.map((x) => x.toLocaleString("zh"))));
// "8,888、9,999"
在稀疏陣列上使用 toLocaleString()
toLocaleString() 將空槽視為與 undefined 相同,併產生一個額外的分隔符。
console.log([1, , 3].toLocaleString()); // '1,,3'
在非陣列物件上呼叫 toLocaleString()
toLocaleString() 方法會讀取 this 的 length 屬性,然後訪問鍵為小於 length 的非負整數的每個屬性。
const arrayLike = {
length: 3,
0: 1,
1: 2,
2: 3,
3: 4, // ignored by toLocaleString() since length is 3
};
console.log(Array.prototype.toLocaleString.call(arrayLike));
// 1,2,3
規範
| 規範 |
|---|
| ECMAScript® 2026 語言規範 # sec-array.prototype.tolocalestring |
| ECMAScript® 2026 國際化 API 規範 # sup-array.prototype.tolocalestring |
瀏覽器相容性
載入中…