【问题标题】:How do you calculate this [duplicate]你如何计算这个[重复]
【发布时间】:2020-12-20 22:42:30
【问题描述】:

var x = 5;
x *= 2;
console.log(++x);

答案 11 怎么样?我很困惑

【问题讨论】:

  • 你期待什么结果?

标签: javascript math operators


【解决方案1】:
var x = 5; // x = 5
x *= 2; // multiply x with 2 (x = 10)
console.log(++x); // console.log x plus 1 (11)

使用这种语法的更常见的方式是加号或减号:

x += 1;
// is a shorthand for
x = x + 1;

x *= 2;
// is a shorthand for
x = x * 2;

// etc.

【讨论】:

    【解决方案2】:

    ++x FIRST 递增,然后使用 THEN,对比:
    x++ FIRST 使用,THEN 递增。

    如果x10
    console.log(++x) 将产生“11”,而:
    console.log(x++) 将产生“10”。

    在这两种情况下,在代码行之后,x 将是 11

    【讨论】:

      【解决方案3】:

      var x = 5;
      x *= 2;
      console.log(x);
      console.log(++x);

      x *= 2; 说:x 将被重新初始化(重新分配)为之前的值 (5) 乘以 2(这给了我们10。 (Useful link - look at chapter Modify-in-place)

      ++x 说:x 将被重新初始化(重新分配)为之前的 (10) 加上 1。此外,返回 xs 新值 (11)。 (In same link, look at the below chapter Increment/Decrement)

      如果我们有 x++,它会说:'将 1 加到 x 但不返回这个新值 - 在我们进行这个加法之前返回值 (10)

      var x = 5;
      x *= 2;
      console.log(x++);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多