String() 和 .toString()的区别
|
zhenglin
2025年12月2日 16:18
本文热度 345
|
String() 和 .toString() 都是把值转成字符串的常见方式,但它们在 调用方式、可用性、返回结果 上有明显区别。
下面我用通俗的方式帮你彻底讲清楚👇
💡 一句话总结

🧩 一、String() 是全局函数
它可以安全地转换任何类型为字符串,包括 null 和 undefined。
String(123) // '123'
String(true) // 'true'
String(null) // 'null'
String(undefined) // 'undefined'
String({ a: 1 }) // '[object Object]'
内部逻辑(简化版):
二、.toString() 是对象的方法
它是定义在大多数对象原型上的方法,比如:
Number.prototype.toString()
Boolean.prototype.toString()
Array.prototype.toString()
Object.prototype.toString()
但 不能对 null 或 undefined 调用,否则直接报错
(123).toString() // '123'
true.toString() // 'true'
[1, 2, 3].toString() // '1,2,3'
({a:1}).toString() // '[object Object]'
null.toString() // ❌ TypeError: Cannot read properties of null
undefined.toString() // ❌ TypeError: Cannot read properties of undefined
三、什么时候用哪个?

举个综合例子:
const values = [123, true, null, undefined, [1,2], {x:1}];
values.forEach(v => {
console.log('String():', String(v));
console.log('toString():', v?.toString?.() ?? '❌ 无 toString 方法');
console.log('---');
});
输出:
String(): 123
toString(): 123
---
String(): true
toString(): true
---
String(): null
toString(): ❌ 无 toString 方法
---
String(): undefined
toString(): ❌ 无 toString 方法
---
String(): 1,2
toString(): 1,2
---
String(): [object Object]
toString(): [object Object]
总结

参考文章:原文链接
该文章在 2025/12/2 16:18:11 编辑过