此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in English Always switch to English

Boolean.prototype.toString()

基线 广泛可用

自 2015年7月 起,此特性已在主流浏览器中得到支持,可在大多数设备和浏览器版本中正常使用。

toString() 方法返回表示指定的布尔对象的字符串。

尝试一下

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 对象的字符串。

描述

Boolean 对象覆盖了 Object 对象的 toString 方法。并没有继承 Object.prototype.toString()。对于布尔对象,toString 方法返回一个表示该对象的字符串。

当一个 Boolean 对象作为文本值或进行字符串连接时,JavaScript 会自动调用其 toString 方法。

对于 Boolean 对象或值,内置的 toString 方法返回字符串 "true""false",具体返回哪个取决于布尔对象的值。

示例

使用 toString()

下面的代码,flag.toString() 返回 "true"

js
const flag = new Boolean(true);
const myVar = flag.toString();

规范

规范
ECMAScript® 2027 Language Specification
# sec-boolean.prototype.tostring

浏览器兼容性

参见