Boolean.prototype.toString()

Baseline 已廣泛支援

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

toString() 方法用於 Boolean 值,以返回表示指定布林值的字串。

試一試

const flag1 = new Boolean(true);

console.log(flag1.toString());
// Expected output: "true"

const flag2 = new Boolean(1);

console.log(flag2.toString());
// Expected output: "true"

語法

js
toString()

引數

無。

返回值

表示指定布林值的字串。

描述

Boolean 物件重寫了 ObjecttoString 方法;它不繼承 Object.prototype.toString()。對於 Boolean 值,toString 方法返回布林值的字串表示形式,即 "true""false"

toString() 方法要求其 this 值是 Boolean 原始值或包裝物件。對於其他 this 值,它會丟擲一個 TypeError,而不嘗試將其強制轉換為布林值。

因為 Boolean 沒有 [Symbol.toPrimitive]() 方法,所以當 Boolean 物件在需要字串的上下文中(例如在 模板字面量中)使用時,JavaScript 會自動呼叫 toString() 方法。然而,布林值原始型別在被強制轉換為字串時,並不會查詢 toString() 方法——而是使用與初始 toString() 實現相同的演算法直接進行轉換。

js
Boolean.prototype.toString = () => "Overridden";
console.log(`${true}`); // "true"
console.log(`${new Boolean(true)}`); // "Overridden"

示例

使用 toString()

js
const flag = new Boolean(true);
console.log(flag.toString()); // "true"
console.log(false.toString()); // "false"

規範

規範
ECMAScript® 2026 語言規範
# sec-boolean.prototype.tostring

瀏覽器相容性

另見