1、JavaScript高级程序设计中第48页
“如果有一个操作数是对象、数值或布尔值,则调用它们的toString()方法取得相应的字符串值,然后再应用前面关于字符串的规则”
function test(){
var a=true;
alert(10+a)
}
test()
如果按照书上讲的运行出来的结果应该是10true
但实际上运行结果是11
2、
function rewrite(num1,num2){
arguments[1]=100;
alert(arguments[0]+num2)
alert(num2)
alert(arguments[1])
}
rewrite(10)
(1)这里的arguments[1]与num2的值不一致,书上说是因为arguments对象的长度由传入参数个数决定(P66)。我不懂这两者有什么关联?
(2)alert(arguments[0]+num2)为什么输出是NaN,而不是10undefined,书上说的是“对于undefined和null,则分别调用String()函数并取得字符串‘undefined’和‘null’”(P48)
以上的书页都是指JavaScript高级程序设计
泻药
问题一
相加的计算:http://www.ecma-international...
可以看到这里的 ToPrimitive 没有给 PreferredType,所以默认 hint 为 number,优先考虑 valueOf 。10 为 10,a 为 true 都不是 string 不满足
所以两者转为数字
true 为 1,相加和为 11
问题二
(1)
看 NOTE1: http://www.ecma-international...
注意这个 less than 。用你上面的例子来说,现在是 non-strict 模式,rewrite(10) 传入 1 个参数,那么 arguments 的索引到 0 为止都是动态绑定的。所以 num2 并没有跟 arguments[1] 绑定在一起。但如果你传入两个或以上的参数,比如 rewrite(10, 1) 就可以观察到两者动态绑定了。
(2)
同理,arguments[0] 为 10,num2 为 undefined,都不是 string,转为 number,undefined 变成 NaN,再加 10 还是 NaN。