【问题标题】:Why doesn't the shorthand arithmetic operator ++ after the variable name return 2 in the following statement?为什么下面语句中变量名后面的速记算术运算符++不返回2?
【发布时间】:2012-06-28 10:02:13
【问题描述】:

我有一个非常简单的算术运算符,但我不知道为什么它不返回 2。下面的代码返回 1。我认为 x++ 等于 x = x + 1;

代码

var x = 1;
document.write(x++);

但是,如果我按如下方式运行代码,它会按预期返回 2

代码

var x = 1;
document.write(++x);

我做错了什么?

【问题讨论】:

  • @Xander - 我知道它们与后增量和预增量有关,但不太明白为什么大多数文章经常将 x++ 引用为与 x = x+1 相同?当它们不返回相同的值时,这是没有意义的。
  • 它与数字加1的效果相同。但是在表达式中使用时效果不同。
  • @nhahtdh - 你能举个例子吗?
  • (x++) * (x++)(x = x + 1) * (x = x + 1) 相比。

标签: javascript


【解决方案1】:

PostIncrement(variable++) & PostDecrement(variable--)

当您在变量后使用++-- 运算符时,在计算表达式并返回原始值之前,变量的值不会递增/递减。例如x++ 转换为类似于以下内容:

document.write(x);
x += 1;

PreIncrement(++variable) & PreDecrement(--variable)

当您在变量之前使用++-- 运算符时,变量的值会在计算表达式之前递增/递减并返回新值。例如++x 转换为类似于以下内容:

x += 1;
document.write(x);

postincrement 和 preincrement 运算符在 C、C++、C#、Java、javascript、php 中可用,我相信还有其他语言。根据why-doesnt-ruby-support-i-or-i-increment-decrement-operators 的说法,Ruby 没有这些运算符。

【讨论】:

  • 抱歉after 声明是什么意思?那么 x++ 和 x = x + 1 不一样呢?
  • 我认为你有它倒退。 ++ 在原地递增变量之前。
  • @Josh Mein - 你能详细说明it is not incremented until after the statement is executed 的意思吗?
  • “语句执行后”对我来说听起来很可疑。后缀运算符的递增发生在将值赋予表达式之后。 x = 1; x++ * x++ 会给 2。
  • @nhahtdh 您认为评估的术语更好吗?
【解决方案2】:

如果您查看javascript specification 第 70 和 71 页,您可以了解它应该如何实现:

前缀:

  1. 设 expr 为计算 UnaryExpression 的结果。
  2. 如果以下条件都为真,则引发 SyntaxError 异常:72 © Ecma International 2011
    • Type(expr) is Reference is true
    • IsStrictReference(expr) 为真
    • Type(GetBase(expr)) 是环境记录
    • GetReferencedName(expr) 是“eval”或“arguments”
  3. 设 oldValue 为 ToNumber(GetValue(expr))。
  4. 让 newValue 为将值 1 与 oldValue 相加的结果,使用与 + 运算符相同的规则(请参阅 11.6.3)。
  5. 调用 PutValue(expr, newValue)。
  6. 返回新值。

或者更简单地说:

  1. 增量值
  2. 返回值

后缀:

  1. 令 lhs 为计算 LeftHandSideExpression 的结果。
  2. 如果以下条件都为真,则抛出 SyntaxError 异常:
    • Type(lhs) is Reference is true
    • IsStrictReference(lhs) 为真
    • Type(GetBase(lhs)) 是环境记录
    • GetReferencedName(lhs) 是“eval”或“arguments”
  3. 设 oldValue 为 ToNumber(GetValue(lhs))。
  4. 让 newValue 为将值 1 与 oldValue 相加的结果,使用与 + 运算符相同的规则(请参阅 11.6.3)。
  5. 调用 PutValue(lhs, newValue)。
  6. 返回旧值。

或者更简单地说:

  1. 为 temp 赋值
  2. 增量值
  3. 返回温度

【讨论】:

    【解决方案3】:

    我认为x++++x(非正式地)是这样的:

    x++

    function post_increment(x) {
      return x; // Pretend this return statement doesn't exit the function
      x = x + 1;
    }
    

    ++x

    function pre_increment(x) {
      x = x + 1;
      return x;
    }
    

    这两个操作做同样的事情,但是它们返回不同的值:

    var x = 1;
    var y = 1;
    
    x++; // This returned 1
    ++y; // This returned 2
    
    console.log(x == y); // true because both were incremented in the end
    

    【讨论】:

      猜你喜欢
      • 2012-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-28
      • 1970-01-01
      • 2013-02-16
      • 2018-04-01
      • 2018-04-27
      相关资源
      最近更新 更多