简体   繁体   English

如何在JavaScript中以线性顺序从数组中减去所有项目?

[英]How to subtract all items from an array in linear order in JavaScript?

I've been able to get the sum of all items using the following code: 我已经可以使用以下代码获取所有项目的总和:

var totalPrice = [60,40];

var total = 0;

   for (var i  = 0; i < totalPrice.length; i++){

      total  += totalPrice[i];

   }

I then tried to subtract all items of the array doing the following: 然后,我尝试执行以下操作减去数组的所有项目:

 totalPrice = [60,40];

var total = 0;

   for (var i  = 0; i < totalPrice.length; i++){

      total  -= totalPrice[i];

   }

This gave me a negative and incorrect output. 这给了我负面和错误的输出。

How would I subtract all items in an array so that in this example, total would be equal to 20. 我如何减去数组中的所有项目,以便在此示例中,总数等于20。

It looks like you're not trying to subtract all items from 0, you're trying to subtract all items except the first from the first. 看来您不是要从0中减去所有项目,而是要从第一个中减去除第一个项目以外的所有项目。 This would be a nice place to use reduce : 这将是使用reduce的好地方:

 const totalPrice = [60, 40]; const total = totalPrice.reduce((a, b) => a - b); console.log(total); 

Using a for loop, you would have to initialize total to the first element, and iterate from the second element onwards: 使用for循环,您必须将total初始化为第一个元素,然后从第二个元素开始进行迭代:

 const totalPrice = [60, 40]; let total = totalPrice[0]; for (var i = 1; i < totalPrice.length; i++) { total -= totalPrice[i]; } console.log(total); 

Since you mentioned, you don't want to end up with negative result and want to do subtraction in linear order, you should make sure that first item of Array is larger than the sum of all other items in the Array. 如前所述,您不想以负数结尾并且想要以线性顺序进行减法,因此应确保Array的第一项大于Array中所有其他项的总和。

And also store the first item of Array in total as below. 并按以下方式总共存储Array的第一项。

 totalPrice = [60,40];

 var total = totalPrice[0];

 for (var i  = 1; i < totalPrice.length; i++){
     total  -= totalPrice[i];
 }

Hope it helps. 希望能帮助到你。

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

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