机制说明
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)'