简体   繁体   English

-- , -= 1 和 - 1 之间的区别

[英]Difference between -- , -= 1 and - 1

I have been working through some freeCodeCamp exercises and while working on a recursion problem in which all the numbers between a given range have to be added to an array (including both the numbers), I came across a problem where the following works:我一直在进行一些 freeCodeCamp 练习,并且在处理递归问题时,必须将给定范围之间的所有数字都添加到数组中(包括两个数字),我遇到了以下问题:

function rangeOfNumbers(startNum, endNum) {
  if (endNum - startNum === 0) {
    return [startNum];
  } else {
    let rangeArray = rangeOfNumbers(startNum, endNum - 1);
    rangeArray.push(endNum);
    return rangeArray;
  }
};

console.log(rangeOfNumbers(8 , 16));

but this doesn't:但这不是:

function rangeOfNumbers(startNum, endNum) {
  if (endNum - startNum === 0) {
    return [startNum];
  } else {
    let rangeArray = rangeOfNumbers(startNum, endNum -= 1);
    rangeArray.push(endNum);
    return rangeArray;
  }
};

console.log(rangeOfNumbers(8 , 16));

There's no error but using the latter (-= 1), I am unable to reach the desired result (the resulting array excludes the upper limit of the range which is 16 in this case and instead includes one extra value of the lower range limit).没有错误,但使用后者(-= 1),我无法达到所需的结果(结果数组不包括范围的上限,在这种情况下为 16,而是包含一个额外的下限值) . Please explain how does the two work differently and the resulting effect in the code posted above.请在上面发布的代码中解释两者的工作方式有何不同以及产生的效果。 Thank You.谢谢你。

PS: I tried googling and even searched Stackoverflow. PS:我尝试了谷歌搜索,甚至搜索了 Stackoverflow。 Coding is new to me and based on what I understood on MDN, 5 - 1 is pretty much the same as x -= 1 (where x = 5).编码对我来说是新的,根据我在 MDN 上的理解,5 - 1 与 x -= 1(其中 x = 5)几乎相同。 Any help in terms of a different explanation is much appreciated.非常感谢任何关于不同解释的帮助。

The difference are:区别在于:

--

i = 1
x = 1 + i-- // i = i - 1 after returning i
// i: 0, x: 2
i = 1
x = 1 + --i // i = i - 1 before returning i
// i: 0, x: 1

-=

i = 1
x = i -= 1 // shorthand of i = i - 1, equals to i--
// i: 0, x: 0

-1

i = 1
x = i - 1 // return i - 1 only and not changing i
// i: 1, x: 0

Refrence: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators参考: https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM