首页 > 试题广场 >

以下代码的输出是什么?```javascriptconst

[单选题]
以下代码的输出是什么?
const obj = {
[Symbol.toPrimitive](hint) {
if (hint === 'number') return 42;
if (hint === 'string') return 'hello';
return true;
}
};
console.log(+obj);
console.log(`${obj}`);
console.log(obj + '');
  • 42 hello hello
  • 42 hello true
  • 42 42 hello
  • NaN hello true
**这段代码的运行结果依次为:** ``` 42 hello true ``` ### 代码原理解释: `Symbol.toPrimitive` 是JavaScript内置的一个 symbol 值,它被用作对象的`ToPrimitive`转换方法,当对象需要被转为原始值时,会优先调用这个方法,并根据传入的`hint`参数(转换提示)返回对应类型的原始值: 1. 当执行`+obj`时,需要将对象转为数字,`hint`为`number`,因此返回`42`,打印结果为`42`; 2. 当执行模板字符串 `${obj}` 时,需要将对象转为字符串,`hint`为`string`,因此返回`hello`,打印结果为`hello`; 3. 当执行`obj + ''`时,属于不明确转换场景,`hint`默认为`default`,因此走`return true`分支,`true + ''`转换为字符串后结果为`true`,打印结果为`true`。
发表于 2026-05-01 10:48:45 回复(0)