JavaScript 如何处理 ++ 操作员?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
来自 ECMAScript 语言规范
这是 postInc 如何工作的伪 javascript 代码:
编辑:正如 mikesamuel 所说:它不是 parseInt。 已更新以反映这一点。
From ECMAScript Language Specification
This is pseudo javascript code of how postInc works:
Edit: As mikesamuel said: it's not parseInt. Updated to reflect that.
下面的代码很好地说明了这一点:
输出为:
一元加将对象转换为数字并且不修改它。 a++ 首先将对象转换为数字,然后返回该数字,然后递增该数字,将值存储在 a 中。
这与另一种可能的解决方案相反,其中 a++ 首先返回对象,然后转换为数字并递增。
The following code illustrates this well:
The output is:
Unary plus converts the object to a number and doesn't modify it. a++ first converts the object to a number, then returns that number, and then increments the number, storing the value in a.
This is opposed to another possible solution, where a++ would first return the object, and then do the conversion to a number and incrementation.
++
运算符执行“toNumber”转换(基本上是类型规则和 valueOf 函数的组合)。 基本上对于任何解析表达式JS 引擎采取的步骤是
对于非原子解析表达式,例如:
base.resolve++
或base["resolve"]++
等。base
仅解析一次,然后重复使用。 在任何理智的情况下,这都是无关紧要的,但是如果要递增的值是一个具有更改基础对象的 valueOf 实现的对象,那么这一点很重要。例如。
The
++
operator does a "toNumber" conversion (basically a combination of type rules and the valueOf function). Basically for any resolve expressionThe steps taken by the JS engine are
For non-atomic resolve expressions, eg.
base.resolve++
orbase["resolve"]++
, etc.base
is resolved only once and then reused. In any sane case this is irrelevant, however it's important if the value being incremented is an object with a valueOf implementation that changes the base object.eg.