Javascript 一个简单的函数,它将数组循环到一个特定的索引,然后将所有的索引相加
我想对提供给函数的索引(paramJavascript 一个简单的函数,它将数组循环到一个特定的索引,然后将所有的索引相加,javascript,arrays,Javascript,Arrays,我想对提供给函数的索引(paramx)之前的所有数字求和。例如,如果我们选择指数2,结果应该是1+2=3 这是我的(不工作)代码: 设arr=[1,2,3,4,5,6,7]; 设和=0; 函数sumforeindex(x){ for(设i=0;i
x
)之前的所有数字求和。例如,如果我们选择指数2,结果应该是1+2=3
这是我的(不工作)代码:
设arr=[1,2,3,4,5,6,7];
设和=0;
函数sumforeindex(x){
for(设i=0;i console.log(sumBeforeIndex(2))//x=在索引上选择随机停止
将返回移动到函数末尾,并且i
应小于x
而不是arr[x]
:
函数sumBeforeIndex(arr,x){
设和=0;
for(设i=0;i
此行错误:
//x could be any integer number and therefore be outside the bounds of the array,
//and if x isn't outside the bounds of the array,
//the number at that index could well be something other than what x is equal to
for(设i=0;i为了(假设i=0;i您的问题是什么?Ohh:D,代码不起作用:/当您在循环内返回时,循环将永远不会完成,返回将在第一次迭代时发生。如果函数被调用
sumBeforeIndex
,我将假定2
的输入仅和1+2
或索引0
和1
-之前的输入重新索引编号2
。好的,@Ori,但“它不工作”不是有效的问题陈述。