试一试
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 对象重写了 Object 的 toString 方法;它不继承 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 |
浏览器兼容性
加载中…