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
    }
4

8 回答 8

4

看起来像这样:

var mySum = 0;
for( var i = 0, len = myArray.length; i < len; i++ ) mySum += myArray[ i ];
于 2013-08-01T15:03:07.000 回答
3
var mySum = 0;
for (var i=0; i < myArray.length; i++) mySum += myArray[i];
于 2013-08-01T15:02:46.343 回答
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]
}
于 2013-08-01T15:03:18.427 回答
2

您可以改用reduce函数将其实现为单行 Javascript 代码。

var sum = myArray.reduce(function(acc, c){return acc + c;}, 0);
于 2013-08-01T15:06:02.697 回答
1

这很容易!

在您的语言中,它看起来像

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
}

在类似 java 的东西中,它看起来像这样

int[] array = new int[100];
int count = 0;
for (int i = 0; i < array.length; i++) {
    count += array[i];
    // i is the loop iterator
}
于 2013-08-01T15:07:05.390 回答
1
for (var = count; count < array.length; count++)
    {
    var mySum +=myArray[count];
}
于 2013-08-01T15:02:41.953 回答
1
var mySum = 0; 
for (var i = 0; i < array.length; i++) {
     var mySum  += array[i];
}
于 2013-08-01T15:03:02.830 回答
1
var mySum = 0; 
for (var = count; count < myArray.length; count++)
{
    mySum +=myArray[count];
}
于 2013-08-01T15:04:28.370 回答