如果放在操作数之后,++运算符将返回原始值-怎么做? [英] ++ operator returns original value if placed after operand — how?

查看:93
本文介绍了如果放在操作数之后,++运算符将返回原始值-怎么做?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我了解,x++本质上是说x = x + 1的更简洁的方式.到目前为止,如此清晰.在前端Javascript中,我偶尔看到过++x —我似乎记得通过 jsPerf 测试可以不再发现(如何有效地使用一个Google ++?),这种方式在特定版本的IE中以某种方式对性能产生了很小的好处,因此就顺其自然.

As far as I've been led to understand, x++ is essentially a terser way of saying x = x + 1. So far, so clear. In front-end Javascript, I've occasionally seen ++x — I seem to remember from a jsPerf test I can no longer find (how does one Google ++ effectively?) that this somehow had a small performance benefit in a particular version of IE, and let it go at that.

但是,我最近遇到了一些在执行顺序(JS代码)方面出现怪异怪癖的事情:

However I've recently encountered something that speaks of a weird quirk in execution order (JS code):

var x = 1;
console.log(x++); // 1 (?!)
console.log(x);   // 2

...而

var x = 1;
console.log(++x); // 2 (what I would've expected)
console.log(x);   // 2

我无法解决这个问题.当操作和赋值在括号内时,如何返回未修改的变量,因此,即使调用console.log,更应执行所有权利,更不用说执行并返回了?

I can't get my head around this. How can we return the unmodified variable when the operation and assignment are within the parenthesis, and thus by all rights should be executed before console.log is even invoked, let alone executed and returned?

推荐答案

这是两件事

x++

后递增.它会在更改前返回x,然后将其更改:

is a post-increment. It returns x before the change but then changes it:

tmp = x;
x = x+1;
return tmp;

++x

预递增.它首先更改x,然后返回新值:

is a pre-increment. It first changes x and returns the new value afterwards:

x = x+1;
return x;

第二个也稍快一些,因为您的编译器/解释器不需要创建临时变量并复制数据.

The second one is also slightly faster as your compliler/interpreter doesn't need to create a temporary variable and copy the data across.

这篇关于如果放在操作数之后,++运算符将返回原始值-怎么做?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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