Object.prototype.toLocaleString()

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

Object 例項的 toLocaleString() 方法返回一個表示該物件的字串。此方法旨在由派生物件為了特定區域設定的目的而覆蓋。

試一試

const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));

console.log(date.toLocaleString("ar-EG"));
// Expected output: "٢٠‏/١٢‏/٢٠١٢ ٤:٠٠:٠٠ ص"

const number = 123456.789;

console.log(number.toLocaleString("de-DE"));
// Expected output: "123.456,789"

語法

js
toLocaleString()

引數

無。但是,所有覆蓋此方法的物件都應最多接受兩個引數,分別對應於 localesoptions,例如 Number.prototype.toLocaleString。引數位置不應用於任何其他目的。

返回值

呼叫 this.toString() 的返回值。

描述

所有繼承自 Object.prototype 的物件(即,除 null-prototype 物件之外的所有物件)都繼承 toLocaleString() 方法。 ObjecttoLocaleString 返回呼叫 this.toString() 的結果。

此函式用於為物件提供一個通用的 toLocaleString 方法,儘管並非所有物件都能使用它。在核心語言中,這些內建物件會覆蓋 toLocaleString 以提供特定於區域設定的格式設定。

示例

使用基礎 toLocaleString() 方法

基礎 toLocaleString() 方法簡單地呼叫 toString()

js
const obj = {
  toString() {
    return "My Object";
  },
};
console.log(obj.toLocaleString()); // "My Object"

Array toLocaleString() 覆蓋

Array.prototype.toLocaleString() 用於透過呼叫每個元素的 toLocaleString() 方法並使用特定於區域設定的分隔符連線結果來將陣列值列印為字串。例如:

js
const testArray = [4, 7, 10];

const euroPrices = testArray.toLocaleString("fr", {
  style: "currency",
  currency: "EUR",
});
// "4,00 €,7,00 €,10,00 €"

Date toLocaleString() 覆蓋

Date.prototype.toLocaleString() 用於打印出更適合特定區域設定的日期顯示。例如:

js
const testDate = new Date();
// "Fri May 29 2020 18:04:24 GMT+0100 (British Summer Time)"

const deDate = testDate.toLocaleString("de");
// "29.5.2020, 18:04:24"

const frDate = testDate.toLocaleString("fr");
// "29/05/2020, 18:04:24"

Number toLocaleString() 覆蓋

Number.prototype.toLocaleString() 用於打印出更適合特定區域設定的數字顯示,例如,帶有正確的分隔符。例如:

js
const testNumber = 2901234564;
// "2901234564"

const deNumber = testNumber.toLocaleString("de");
// "2.901.234.564"

const frNumber = testNumber.toLocaleString("fr");
// "2 901 234 564"

規範

規範
ECMAScript® 2026 語言規範
# sec-object.prototype.tolocalesstring

瀏覽器相容性

另見