我想改写这一行:
var mySum = myArray[0] + myArray[1] + myArray[2] + myArray[3];
考虑到我不知道数组中的许多元素,我想到了这个:
for (var = count; count < array.length; count++)
{
var mySum = ?? // but what's the math for this
}
答案 0 :(得分:4)
似乎是这样的:
var mySum = 0;
for( var i = 0, len = myArray.length; i < len; i++ ) mySum += myArray[ i ];
答案 1 :(得分:3)
var mySum = 0;
for (var i=0; i < myArray.length; i++) mySum += myArray[i];
答案 2 :(得分: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]
}
答案 3 :(得分:2)
您可以使用reduce函数将其实现为单行Javascript代码。
var sum = myArray.reduce(function(acc, c){return acc + c;}, 0);
答案 4 :(得分:1)
for (var = count; count < array.length; count++)
{
var mySum +=myArray[count];
}
答案 5 :(得分:1)
var mySum = 0;
for (var i = 0; i < array.length; i++) {
var mySum += array[i];
}
答案 6 :(得分:1)
var mySum = 0;
for (var = count; count < myArray.length; count++)
{
mySum +=myArray[count];
}
答案 7 :(得分: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
}