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
这篇关于查找嵌套数组的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:查找嵌套数组的总和


- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- 失败的 Canvas 360 jquery 插件 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- Flexslider 箭头未正确显示 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01