为什么 JavaScript 的后增量运算符与 C 和 Perl 不同? [英] Why is JavaScript's post-increment operator different from C and Perl?

查看:47
本文介绍了为什么 JavaScript 的后增量运算符与 C 和 Perl 不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在学习 JavaScript 考试.我还对 C 和 Perl 有所了解,因此我熟悉所有三种语言中的前缀和后缀运算符.

I'm studying for an exam on JavaScript at the moment. I've also got a little knowledge of C and Perl so I'm familiar with prefix and postfix operators in all three languages.

我为此做了一次在线模拟考试,我犯的一个错误是在评估以下代码时:

I did an online practice exam for it and one mistake I made was in evaluating the following code:

var x = 10;
x += x--;

现在,我认为它会评估为 19,因为它将是 10 + 10,然后减去 1 得到 9.但我得到的反馈是它是错误的,实际上评估为 20.我觉得这听起来有点可疑,所以我在 HTML 文档中对其进行了测试,结果再次显示为 20.然后我尝试了 C 和 Perl 中的等效项,结果都为 19.

Now, I thought it would evaluate to 19 because it would be 10 + 10, then subtract 1 to make 9. But the feedback I got was that it was wrong and it actually evaluates to 20. I thought that sounded a bit suspicious so I tested it out in an HTML document, and it came out with 20 again. I then tried the equivalents in C and Perl and both evaluated to 19.

谁能向我解释为什么 JavaScript 将答案评估为 20 而其他语言将其评估为 19?我从测试中得到的答案对我来说不太清楚:

Can anyone explain to me why JavaScript evaluates the answer as 20 when other languages evaluate it to 19? The answer I got from the test wasn't too clear to me:

增量++and decrement -- 可以放置运算符在操作数之前或之后.如果增加或减少操作符放在操作数之前,操作立即发生.如果递增或递减运算符放在操作数之后,则操作数值的变化直到下一次在程序中访问操作数.因此表达式 x += x-- 等价于 x = x +10 计算结果为 20.

The increment ++ and decrement -- operators can be placed either before or after an operand. If the increment or decrement operator is placed before the operand, the operation occurs immediately. If the increment or decrement operator is placed after the operand, the change in the operand's value is not apparent until the next time the operand is accessed in the program. Thus the expression x += x-- is equivalent to x = x + 10 which evaluates to 20.

推荐答案

扩展语句

x += x--;

到更详细的 JS 代码

to the more verbose JS code

x = x + (function(){ var tmp = x; x = x - 1; return tmp; })();

结果完全合理,因为它将评估为

the result makes perfect sense, as it will evaluate to

x = 10 + (function(){ var tmp = 10; x = 10 - 1; return tmp; })();

即 20.记住 JS 从左到右计算表达式,包括复合赋值,即 x 的值在执行 x-- 之前被缓存.

which is 20. Keep in mind that JS evaluates expressions left-to-right, including compound assignments, ie the value of x is cached before executing x--.

你也可以这样想:假设从左到右求值顺序,JS将赋值解析为

You could also think of it this way: Assuming left-to-right evaluation order, JS parses the assignment as

x := x + x--

而 Perl 将使用

x := x-- + x

我没有看到任何令人信服的论据支持或反对这两种选择,因此不同语言的行为不同只是运气不好.

I don't see any convincing arguments for or against either choice, so it's just bad luck that different languages behave differently.

这篇关于为什么 JavaScript 的后增量运算符与 C 和 Perl 不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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