Walter Purvis Walter Purvis - 1 year ago 92
Javascript Question

add array together, display sum

What i am trying to do is take the user input which is numbers then add those numbers together and display the sum.

I have an array, I have the sum of the array. Now I need to display only the sum. It seems my loop is outputting all the numbers in the array.

function hello(){


var arr = []; // define our array

for (var i = 0; i < 3; i++) { // loop 10 times
arr.push(prompt('Enter number' + (i+1))); // push the value into the array
}

alert('Full array: ' + arr.join(', ')); // alert the result`

var total = 0;
for(i=0; i<arr.length; i++){
var number = parseInt(arr[i], 10);
total += number;
console.log(total);

// gets the last element in arr[] array //does not give answer
var totalArr = arr[i][arr[i].length-1];
}

console.log(totalArr);

Answer Source

Well if you want just the total output at the end then you need to log total to the console after the loop. Based on my understanding of what you want to do I think something like the following is all that's needed...

function hello() {
    var arr = [];

    for (var i = 0; i < 10; i++) {
        arr.push(prompt('Enter number' + (i+1)));
    }

    var total = 0;

    for(i=0; i<arr.length; i++) {
        var number = parseInt(arr[i], 10);
        total += number;
    }

    console.log(total);
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download