gpt4 book ai didi

Javascript 权威指南 : the confusion of steps of converting object to a string

转载 作者:数据小太阳 更新时间:2023-10-29 04:41:41 25 4
gpt4 key购买 nike

根据 Javascript 权威指南第 6 版 3.8.3 节:

To convert an object to a string, JavaScript takes these steps:
• If the object has a toString() method, JavaScript calls it. If it returns a primitive value, JavaScript converts that value to a string (if it is not already a string) and returns the result of that conversion. Note that primitive-to-string conversions are all well-defined in Table 3-2.

• If the object has no toString() method, or if that method does not return a primitive value, then JavaScript looks for a valueOf() method. If the method exists, JavaScript calls it. If the return value is a primitive, JavaScript converts that value to a string (if it is not already) and returns the converted value.

• Otherwise, JavaScript cannot obtain a primitive value from either toString() or valueOf(), so it throws a TypeError.

例如:

var obj = {
toString: function() {
console.log('toStirng...');
return 90;
},
valueOf: function() {
console.log('valueOf...');
return 80;
}
}

console.log(obj + '');

因此,上面的代码片段会将 obj 转换为字符串,因为 obj + '',所以它应该打印:

toString...
90

但实际上,它打印:

valueOf...
80

那怎么了? obj + '' 不会将 obj 转换为字符串吗?

最佳答案

this 中很好地说明文章:

因为+''利用了ToPrimitive(Number)内部方法。如果您运行 String(obj),您将收到 toString 方法结果。

关于Javascript 权威指南 : the confusion of steps of converting object to a string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45155909/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com