JavaScript中的x ++有什么作用? [英] What does x++ in JavaScript do?
本文介绍了JavaScript中的x ++有什么作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个很短的问题,但这确实使我感到困惑.
I have a very short question, but it really confused me.
var y = 3, x = y++;
x的值是什么?
我认为答案应该是4,但实际上是3.
I thought the answer should be 4, but actually it's 3.
有人可以向我解释原因吗?
Can anyone explain me the reason?
推荐答案
y ++
被称为 post-increment (后递增)-在变量之后它会递增变量>它返回原始值作为表达式的值.所以
y++
is called post-increment -- it increments the variable after it returns the original value as the value of the expression. So
x = y++;
等效于:
temp = y;
y = y + 1;
x = temp;
如果要返回新值,则应使用 ++ y
.之所以称为 pre-increment ,是因为它会在返回变量 之前将其递增.声明
If you want to return the new value, you should use ++y
. This is called pre-increment because it increments the variable before returning it. The statement
x = ++y;
等效于:
y = y + 1;
x = y;
这篇关于JavaScript中的x ++有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文