How to concatenate an array of number into one total number?

时间:2015-10-31 00:14:16

标签: javascript arrays loops push

I'm trying to take an array of any length of ints, and concatenate it into a single number that is the total added up. For instance, if I have an array that goes as follows: [2, 2] I want it to becomes [4]. I'm currently using a for loop to generate the array using .push() on checkboxes and require the total to add it to another equation. I'm trying to do this for the price array: for(var i=0; i < toppings.length; i++){ // CREATES LOOP FOR EXTRA DATA if(toppings[i].checked) { //IF CHECKED storeExtNames += products[productsList.selectedIndex].extra[i].name + " "; storeExtPrice.push(products[productsList.selectedIndex].extra[i].price); }//END IF }//END LOOP

1 个答案:

答案 0 :(得分:2)

你可以像这样遍历数组:

var arr = [ 1, 2, 3, 4, 5, 6 ];
while (arr.length > 1) {
    arr[0] += arr.pop();
}