1

I want to rewrite this line:

var mySum = myArray[0] + myArray[1] + myArray[2] + myArray[3];

Considering that I do not know a number of elements in the array, I am thinking of this:

 for (var = count; count < array.length; count++)
    {
    var mySum = ?? // but what's the math for this
    }

8 Answers 8

4

Seems like this:

var mySum = 0;
for( var i = 0, len = myArray.length; i < len; i++ ) mySum += myArray[ i ];
3
var mySum = 0;
for (var i=0; i < myArray.length; i++) mySum += myArray[i];
3
var mySum = 0;
var myArray = [1,2,3,5,8,13]

for(var i = 0,amount = myArray.length;i < amount;i++) {
    mySum = mySum + myArray[i]
}
2

You can use reduce function instead to implement it as single-line Javascript code.

var sum = myArray.reduce(function(acc, c){return acc + c;}, 0);
1

This is rather easy!

In your language it would look like

var mySum = 0;
for (var count = 0; count < array.length; count++) {
     mySum += array[count];
    // mySum = mySum + array[count]
    // note that I declared mySum outside the loop
}

In something like java it would look like this

int[] array = new int[100];
int count = 0;
for (int i = 0; i < array.length; i++) {
    count += array[i];
    // i is the loop iterator
}
1
for (var = count; count < array.length; count++)
    {
    var mySum +=myArray[count];
}
1
var mySum = 0; 
for (var i = 0; i < array.length; i++) {
     var mySum  += array[i];
}
1
var mySum = 0; 
for (var = count; count < myArray.length; count++)
{
    mySum +=myArray[count];
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.