【问题标题】:Can someone explain why the incrementing below is not adding a +1 [duplicate]有人可以解释为什么下面的递增没有添加+1 [重复]
【发布时间】:2020-01-13 10:49:23
【问题描述】:

谁能帮我解释一下为什么会这样

let one = 1;

function chg(arg) {
  return arg++ // --> shouldn't this be similar to arg + arg? but it's outputting 1
}

console.log(one);
console.log(chg(one));

【问题讨论】:

  • 如果one 是1。然后one++ 是1 和one 变成2。你要找的是++one。
  • 如果你使用return ++args;,它就可以工作。见stackoverflow.com/questions/3469885/…
  • 原始值作为值传递,而不是作为参考。
  • 这能回答你的问题吗? ++someVariable vs. someVariable++ in JavaScript
  • 这段代码有两个问题。在另一个答案中说明了第一个具有后增量的。但是数据类型编号还有另一个问题。它是一个原始类型,您将它传递给一个实际上将值one 复制到arg 的函数。 arg 在返回后递增,但立即被遗忘。 one = chg(one) 会与 return ++arg 一起改变你的价值

标签: javascript


【解决方案1】:

x++为后自增表达式,即其值为x,返回该值后,变量加一。

++x 是预增表达式,即x 先增一,然后返回。

你会在这里需要++x——或者因为这是一个函数参数,所以更清楚并使用x + 1; ++ 修改无论如何都没有效果。

【讨论】:

  • 最后一句话很关键,因为我已经可以预料到“为什么chg(one); chg(one);没有继续增加?”跟进。
  • 这不是一回事,“one”+1 将返回“one1”,而“one”++ 将返回 NaN
【解决方案2】:

试试下面的代码。您需要使用前增量而不是后增量

let one = 1;

function chg(arg) {
  return ++arg // --> shouldn't this be similar to arg + arg? but it's outputting 1
}

console.log(one);
console.log(chg(one));

【讨论】:

    【解决方案3】:
    let one = 1;
    
    function chg(arg) {
      return arg+1 // This is more readable code
    }
    
    console.log(one);
    console.log(chg(one));
    

    【讨论】:

      【解决方案4】:

      刚刚编辑了您的代码:

      let one = 1;
      
      function chg(arg) {
        return ++arg; 
      }
      
      console.log(one);
      console.log(chg(one));
      

      或者也可以这样

      let one = 1;
      
      function chg(arg) {
        return arg;
      }
      
      console.log(one);
      console.log(chg(++one));
      

      【讨论】:

      • 所以这意味着,在前面放一个++会返回我存储1的内存,然后在它的位置添加一个1?另外,为什么我把它放在一个函数中会有所不同。如果假设我改为如下所示,它会正确递增。 let one = 1; one++ function chg(arg) { return ++arg // --> shouldn't this be similar to arg + arg? but it's outputting 1 } console.log(one); console.log(chg(one));
      • 这里的变量 arg 不是按引用移动,而是按值移动。
      • 抱歉,我需要一段时间来编辑它
      猜你喜欢
      • 2020-10-27
      • 1970-01-01
      • 1970-01-01
      • 2022-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多