[英]How to subtract all items from an array in linear order in JavaScript?
我已經可以使用以下代碼獲取所有項目的總和:
var totalPrice = [60,40];
var total = 0;
for (var i = 0; i < totalPrice.length; i++){
total += totalPrice[i];
}
然后,我嘗試執行以下操作減去數組的所有項目:
totalPrice = [60,40];
var total = 0;
for (var i = 0; i < totalPrice.length; i++){
total -= totalPrice[i];
}
這給了我負面和錯誤的輸出。
我如何減去數組中的所有項目,以便在此示例中,總數等於20。
看來您不是要從0中減去所有項目,而是要從第一個中減去除第一個項目以外的所有項目。 這將是使用reduce
的好地方:
const totalPrice = [60, 40]; const total = totalPrice.reduce((a, b) => a - b); console.log(total);
使用for
循環,您必須將total
初始化為第一個元素,然后從第二個元素開始進行迭代:
const totalPrice = [60, 40]; let total = totalPrice[0]; for (var i = 1; i < totalPrice.length; i++) { total -= totalPrice[i]; } console.log(total);
如前所述,您不想以負數結尾並且想要以線性順序進行減法,因此應確保Array的第一項大於Array中所有其他項的總和。
並按以下方式總共存儲Array的第一項。
totalPrice = [60,40];
var total = totalPrice[0];
for (var i = 1; i < totalPrice.length; i++){
total -= totalPrice[i];
}
希望能幫助到你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.