Finding the sum of a nested array(查找嵌套数组的总和)
问题描述
我试图找到一个嵌套数组的所有数字的总和,但我没有让它正常工作.这是我尝试过的:
I tried finding the sum of all numbers of a nested array, but I don't get it to work correctly. This is what I tried:
function arraySum(i) {
sum = 0;
for (a = 0; a < i.length; a++) {
if (typeof i[a] == 'number') {
sum += i[a];
} else if (i[a] instanceof Array) {
sum += arraySum(i[a]);
}
}
return sum;
}
当您尝试使用数组 [[1,2,3],4,5]
时,它会得到 6
作为答案,而不是 15代码>.有人知道哪里有错吗?
When you try it out with the array [[1,2,3],4,5]
, it gets 6
as the answer, instead of 15
.
Does somebody know where there is a mistake in it?
推荐答案
你的代码的问题是 sum
和 a
变量是全局的,而不是局部的.因此,您会得到一个无限循环(函数中第一个条目的 a 被第二个条目重置,因此再次处理相同的元素).
The problem with your code is that the sum
and a
variables are global, instead of local. Because of this you get an infinite loop (a from the first entry in the function is reset by the second entry, so the same elements are processed again).
通过将 var
添加到声明 sum
和 a
的位置来修复它,以使它们成为函数的局部变量:
Fix it by adding var
to where sum
and a
are declared to make them local to the function:
function arraySum(i) {
var sum=0; // missing var added
for(var a=0;a<i.length;a++){ // missing var added
if(typeof i[a]=="number"){
sum+=i[a];
}else if(i[a] instanceof Array){
sum+=arraySum(i[a]);
}
}
return sum;
}
演示:http://jsbin.com/eGaFOLA/2/edit
这篇关于查找嵌套数组的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:查找嵌套数组的总和


基础教程推荐
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- Bokeh Div文本对齐 2022-01-01