Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/387.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 一个简单的函数,它将数组循环到一个特定的索引,然后将所有的索引相加_Javascript_Arrays - Fatal编程技术网

Javascript 一个简单的函数,它将数组循环到一个特定的索引,然后将所有的索引相加

Javascript 一个简单的函数,它将数组循环到一个特定的索引,然后将所有的索引相加,javascript,arrays,Javascript,Arrays,我想对提供给函数的索引(paramx)之前的所有数字求和。例如,如果我们选择指数2,结果应该是1+2=3 这是我的(不工作)代码: 设arr=[1,2,3,4,5,6,7]; 设和=0; 函数sumforeindex(x){ for(设i=0;i

我想对提供给函数的索引(param
x
)之前的所有数字求和。例如,如果我们选择指数2,结果应该是1+2=3

这是我的(不工作)代码:

设arr=[1,2,3,4,5,6,7];
设和=0;
函数sumforeindex(x){
for(设i=0;iconsole.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,但“它不工作”不是有效的问题陈述。