javascript - 加性操作符疑问

查看:78
本文介绍了javascript - 加性操作符疑问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

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...

Let lprim be ? ToPrimitive(lval).
Let rprim be ? ToPrimitive(rval).

可以看到这里的 ToPrimitive 没有给 PreferredType,所以默认 hint 为 number,优先考虑 valueOf 。10 为 10,a 为 true 都不是 string 不满足

If Type(lprim) is String or Type(rprim) is String

所以两者转为数字

Let lnum be ? ToNumber(lprim).
Let rnum be ? ToNumber(rprim).

true 为 1,相加和为 11

问题二

(1)

看 NOTE1: http://www.ecma-international...

For non-strict functions the integer indexed data properties of an arguments object whose numeric name values are less than the number of formal parameters of the corresponding function object initially share their values with the corresponding argument bindings in the function's execution context. This means that changing the property changes the corresponding value of the argument binding and vice-versa. This correspondence is broken if such a property is deleted and then redefined or if the property is changed into an accessor property. For strict mode functions, the values of the arguments object's properties are simply a copy of the arguments passed to the function and there is no dynamic linkage between the property values and the formal parameter values.

注意这个 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。

这篇关于javascript - 加性操作符疑问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆