繁体   English   中英

如何从 JavaScript 中的数组中减去数字?

[英]How can I subtract numbers from array in JavaScript?

例如: [5, 4, 1] = 0 如果这是一个简单的问题,我很抱歉,但我是 JavaScript 新手! 感谢所有答案

使用Array.prototype.reduce将 Array减少到单个输出:

 const numbers = [5, 4, 1]; const sub = numbers.reduce((acc, num) => acc - num); console.log(sub) // 0

使用 for 循环和 if else:

 const numbers = [5,4,1] ; let ans = 0; //Initialize ans with some value if(numbers.length > 0) ans = numbers[0]; //If array has length >0, use the first value. This will let you handle single length arrays for(let i = 1; i < numbers.length;i++){ ans -= numbers[i]; //subtract for every other element } console.log(ans);

您可以在 mozilla 文档上查看Array.reduce函数。

const subtractNumbersFromArray = (arr) => {
  return arr.reduce((acc, currentValue) => acc - currentValue);
};

const result = subtractNumbersFromArray([5, 4, 1]) // 0
const result = subtractNumbersFromArray([10, 3, 2]) // 5

暂无
暂无

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

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