JavaScript使用对象进行有趣的自动转换:
var o = {toString: function() {return "40"; }}; print(o + o); print((o+1)+o); print((o*2) + (+o));将打印:
4040 40140 120这是因为+,如果有任何参数是对象/字符串,它会尝试将所有参数转换为字符串,然后连接它们。 如果所有参数都是数字,它将它们加在一起。 *和一元+使用toString将对象转换为数字(以及valueOf,此处未显示)。
JavaScript为++运算符做了什么?
JavaScript does funky automatic conversions with objects:
var o = {toString: function() {return "40"; }}; print(o + o); print((o+1)+o); print((o*2) + (+o));will print:
4040 40140 120This is because +, if any of the arguments are objects/strings, will try to convert all the arguments to strings then concatenate them. If all arguments are numbers, it adds them together. * and unary + convert objects to numbers using toString (as well as valueOf, not shown here).
What does JavaScript do for the ++ operator?
最满意答案
从ECMAScript语言规范
11.3后缀表达式
句法
PostfixExpression:
LeftHandSideExpression LeftHandSideExpression [这里没有LineTerminator] ++ LeftHandSideExpression [这里没有LineTerminator] -11.3.1后缀增量运算符
制作PostfixExpression:LeftHandSideExpression [这里没有LineTerminator] ++的计算方法如下:
评估LeftHandSideExpression。 调用GetValue(Result(1))。 呼叫号码(结果(2))。 使用与+运算符相同的规则(第11.6.3节)将值1添加到结果(3)。 呼叫PutValue(结果(1),结果(4))。 返回结果(3)。
这是postInc工作原理的伪javascript代码:
function postInc(a) { var x = +a; // Converts a to a number, Section 11.4.6 Unary + Operator a = x + 1; return x; }编辑:正如mikesamuel所说:这不是parseInt。 更新以反映这一点。
From ECMAScript Language Specification
11.3 Postfix Expressions
Syntax
PostfixExpression :
LeftHandSideExpression LeftHandSideExpression [no LineTerminator here] ++ LeftHandSideExpression [no LineTerminator here] --11.3.1 Postfix Increment Operator
The production PostfixExpression : LeftHandSideExpression [no LineTerminator here] ++ is evaluated as follows:
Evaluate LeftHandSideExpression. Call GetValue(Result(1)). Call ToNumber(Result(2)). Add the value 1 to Result(3), using the same rules as for the + operator (section 11.6.3). Call PutValue(Result(1), Result(4)). Return Result(3).
This is pseudo javascript code of how postInc works:
function postInc(a) { var x = +a; // Converts a to a number, Section 11.4.6 Unary + Operator a = x + 1; return x; }Edit: As mikesamuel said: it's not parseInt. Updated to reflect that.
更多推荐
发布评论