想了解 String() 全局函数和 .toString() 方法的区别,这是 JavaScript 中常见的类型转换知识点,我会从用法、兼容性、边界场景三个维度帮你讲清楚,新手也能轻松理解。
核心区别总览
表格
| 特性 | String() 全局函数 |
.toString() 方法 |
|---|---|---|
| 调用方式 | 函数调用(String(xxx)) |
实例方法调用(xxx.toString()) |
| 空值处理 | 可处理 null/undefined(不报错) |
处理 null/undefined 直接报错 |
| 原始值处理 | 直接转换原始值(如数字、布尔) | 原始值会先装箱为对象,再调用方法 |
| 返回结果 | 所有合法输入都返回字符串 | 仅非空值能返回字符串,空值抛错 |
| 适用场景 | 不确定值是否为 null/undefined 时 |
确定值为非空原始值 / 对象时 |
总结
-
核心差异 :
String()能安全处理null/undefined,.toString()会抛错; -
结果一致场景:处理非空原始值(数字、布尔、字符串)时,两者返回结果相同;
-
特殊能力 :
.toString()支持数字进制转换,String()无此功能; -
开发建议:
- 不确定值是否为空 → 用
String(); - 确定值非空 + 需进制转换 → 用
.toString(); - 处理对象 / 数组 → 两者结果一致,任选即可。
- 不确定值是否为空 → 用
具体用法&差异详解
处理 null/undefined(最核心区别)
这是两者最关键的差异,也是实际开发中最容易踩坑的点:
js
// 1. String() 处理 null/undefined → 不报错,返回对应字符串
console.log(String(null)); // "null"
console.log(String(undefined)); // "undefined"
// 2. .toString() 处理 null/undefined → 直接抛 TypeError
console.log(null.toString()); // Uncaught TypeError: Cannot read properties of null (reading 'toString')
console.log(undefined.toString());// Uncaught TypeError: Cannot read properties of undefined (reading 'toString')
处理原始值(数字、布尔、字符串)
两者结果一致,但底层逻辑不同:
js
// 数字
console.log(String(123)); // "123"
console.log((123).toString()); // "123"
// 布尔
console.log(String(true)); // "true"
console.log(true.toString()); // "true"
// 空字符串
console.log(String('')); // ""
console.log(''.toString()); // ""
// 特殊数字(NaN/Infinity)
console.log(String(NaN)); // "NaN"
console.log(NaN.toString()); // "NaN"
底层差异:String(123) 直接转换原始数字;(123).toString() 会先把 123 装箱为 Number 对象(new Number(123)),再调用对象的 toString() 方法。
处理对象(数组、普通对象)
String()会调用对象的toString()方法(等同于obj.toString());- 普通对象的
toString()默认返回"[object Object]",数组的toString()会拼接元素:
js
// 数组
const arr = [1, 2, 3];
console.log(String(arr)); // "1,2,3"
console.log(arr.toString()); // "1,2,3"
// 普通对象
const obj = { a: 1 };
console.log(String(obj)); // "[object Object]"
console.log(obj.toString()); // "[object Object]"
// 自定义对象(重写 toString)
const customObj = {
toString() {
return "自定义字符串";
}
};
console.log(String(customObj)); // "自定义字符串"
console.log(customObj.toString());// "自定义字符串"
处理空字符串 / 空值的边界场景
js
// 空字符串
console.log(String('')); // ""
console.log(''.toString()); // ""
// 0/空数组
console.log(String(0)); // "0"
console.log((0).toString()); // "0"
console.log(String([])); // ""
console.log([].toString()); // ""
实际开发中的选择建议
优先用 String()
当你不确定要转换的值是否为 null/undefined 时(比如接口返回值、用户输入、变量可能未初始化),String() 更安全,不会报错。
js
// 示例:处理接口返回的可能为空的值
const res = { data: null };
const str = String(res.data); // "null"(不报错)
用 .toString() 的场景
当你明确知道值是非空的原始值 / 对象时(比如数字、数组),可以用 .toString(),语义更清晰。
js
// 示例:数字转指定进制字符串(toString 支持参数,String 不支持)
console.log((10).toString(2)); // "1010"(转二进制)
console.log((10).toString(16)); // "a"(转十六进制)
补充:Number.prototype.toString(radix) 支持传入进制参数(2-36),这是 String() 没有的功能。