← 中文资源

简体中文版本

String() 万能转换,toString() 遇空值抛错

String() 对任何值都能给出字符串,连 Symbol 也不放过;.toString() 是方法调用,落在 null/undefined 上直接抛 TypeError。可能为空的入参用 String() 兜底更稳。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

42
3.14
true
null
undefined
Symbol(id)
1,2
null.toString() -> TypeError
label of null: (unset)
label of 0: 0

机制说明

values 覆盖数字、布尔、null、undefined、Symbol 与数组。String() 全部打印成功——42、3.14、true、null、undefined、Symbol(id) 与 1,2——函数形式可以把任何值转成文本。

方法调用没有这么宽容:null.toString() 抛 TypeError,被捕获并打印。实践规则落在 toLabel:空值变成 (unset) 标记,而 0 是真实值,原样保留 0 而不是被当成未设置。

注意事项

  • String(symbol) 可行;String 是唯一能处理 symbol 的转换。
  • 用 value == null 守卫,避免把 0 与 false 误判为缺失。

核心语句

const toLabel = (value) => (value == null ? '(unset)' : String(value));

代码示例

// String() coerces any value to a string; .toString() is a method call that throws on nullish receivers
const values = [42, 3.14, true, null, undefined, Symbol('id'), [1, 2]];

for (const value of values) {
  console.log(String(value));
}

// String() prints nullish values, while a method call on null throws TypeError
try {
  null.toString();
} catch (error) {
  console.log('null.toString() ->', error.constructor.name);
}

// Practical rule: use String() for possibly-null input instead of guard-then-toString
const toLabel = (value) => (value == null ? '(unset)' : String(value));
console.log('label of null:', toLabel(null));
console.log('label of 0:', toLabel(0)); // 0 is a real value, not replaced by '(unset)'