簡體   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