为什么JavaScript的后缀符号与C和Perl不同? [英] Why is JavaScript's postfix notation different from C and Perl?

查看:78
本文介绍了为什么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 notation 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到但是我得到的反馈是错误的,实际上估计为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.

有人可以向我解释为什么当其他语言将其评估为19时,JavaScript会将答案评估为20吗?我从测试中得到的答案对我来说不太清楚:

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:


增量++
和减量 - 运算符可以在操作数之前或之后放置
。如果增量或减量
运算符放在操作数之前,则操作立即发生。
如果增量或减量运算符位于操作数之后,则操作数值中的
更改在下一次在程序中访问
操作数之前不会显现。因此,表达式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代码

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天全站免登陆