JavaScript如何处理++运算符?(How does JavaScript treat the ++ operator?)

编程入门 行业动态 更新时间:2024-10-14 14:14:16
JavaScript如何处理++运算符?(How does JavaScript treat the ++ operator?)

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 120

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

更多推荐

本文发布于:2023-04-27 11:25:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1326425.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何处理   运算符   JavaScript   treat   operator

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!