javascript - 如何在JavaScript中计算数组中从最后一个到第一个元素之间的差异?

标签 javascript arrays for-loop

这是一个给定的数组:

arrayNum = [1, 2, 4, 5, 8, 9];
arrayS = [];
for(var i=1, len = array1.length; i<len; i++){
    arrayS.push(arrayNum[i]-arrayNum[i-1]);
  }
console.log(arrayS);

这段代码计算每两个连续元素之间的差异! 但是我需要计算从最后一个元素到第一个元素之间的差异,在这种特殊情况下 9-8-5-4-2-1 = -11?!

s1=0;
for(var j=array1[array1.length-1]; j>0; j--){
    s1 = s1 - array1[j];
  }
console.log(s1);

但是这不起作用!

最佳答案

在原始解决方案中,您应该迭代索引,而不是元素

const arrayNum = [1, 2, 4, 5, 8, 9];

s1 = arrayNum[arrayNum.length - 1];
for (var j = arrayNum.length - 2; j >= 0; j--) {
  s1 = s1 - arrayNum[j];
}
console.log(s1);

或者你可以使用reduce

const arrayNum = [1, 2, 4, 5, 8, 9];

const res = arrayNum.reduce(
  (acc, el, index) => acc + (index !== arrayNum.length - 1 ? -1 : 1) * el,
  0
);

console.log(res);

关于javascript - 如何在JavaScript中计算数组中从最后一个到第一个元素之间的差异?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66075301/

相关文章:

javascript - mongodb 驱动程序不释放资源

javascript - Angular导出导入对象(获取对象数据)

更改数组元素的代码会更改不同的变量

连接两个字符数组 C

python - 有什么办法可以缩短这个 Python 生成器表达式吗?

java - 为什么这两个 for 循环给出不同的结果?

javascript - 正则表达式 JavaScript 捕获直到(之前)可选字符串

javascript - 如何在 JavaScript 中顺序执行代码

javascript - 如何更改对象列表的每个元素中的字符串部分?

c - 为什么我的 for 循环没有在 C 中给出预期的输出?