分配时Javascript增量 [英] Javascript increment while assigning

查看:105
本文介绍了分配时Javascript增量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在讨论前缀增量运算符,我们似乎遇到了分歧。

I was having a conversation about the prefix increment operator, and we seem to have run into a disagreement.

运行此代码时:

var x = 0;
x = ++x;

是第二行相当于:


  • x =(x = x + 1)OR

  • x =(x + 1)

很难区分,因为结果是相同的(两者都导致 x 的值为1)

It is hard to tell the difference because the results are identical (both result in x having a value of 1)

我认为当赋值的左边是变量本身时,该值不会保存到原始变量中。

I believe that the value is not saved to the original variable when the left hand side of the assignment is the variable itself.

我的对手不同意并认为只要使用 ++ 运算符,该值就会保存到原始变量中。

My counterpart disagrees and thinks the value is saved to the original variable whenever the ++ operator is used.

我们哪一个是对的?

推荐答案

它已保存,所以它与第一个例子类似。
以此代码为例:

It is saved, so it is similar to the first example. Take for example this code:

var v = 0;
v = ++v + ++v + ++v;
// Returns 6

这是因为这将转化为:

v = (0+1) + ((0+1)+1) + (((0+1)+1)+1);

或者,更准确:

v = 0+1 +
v = 1+1 + //Previous value of v + 1
v = 2+1   //Previous value of v + 1

为什么?

++ v 将首先保存增量值v,然后它将返回此增量值。

为简化起见,请在控制台中尝试:

++v will first save the incremented value of v, then it will return this incremented value.
To simplify things, try this in your console:

x = 0;
++x;

如果 ++ x 将解析为 x + 1 x 的值现在仍为 0 ,对吗?

不,你的 x 将是 1 。这意味着 ++ x 必须有一个赋值运算符。

If ++x would resolve to x + 1, the value of x would now still be 0, right?
Nope, your x will be 1. This means that ++x must have a assignment operator in there.

这篇关于分配时Javascript增量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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