可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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; }
Does somebody know where there is a mistake in it? When you try it out with the array [[1,2,3],4,5], it gets 6 as answer, instead of 15. I don't know why.
回答1:
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).
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; }
Demo: http://jsbin.com/eGaFOLA/2/edit
回答2:
Recurse, for example
function arraySum(x) { var sum = 0, i; if (typeof x === 'number') return x; else if (x instanceof Array) for (i = 0; i < x.length; ++i) sum += arraySum(x[i]); return sum; } arraySum([[1,2,3],4,5]); // 15
I didn't optimise this so that it's clear, you may want some more logic before recursion.
The reason yours isn't working is because you need to var
both sum
and a
.
回答3:
You're missing two var
in there. You've implicitly declared sum
and a
at window scope:
function arraySum(i) { **var** sum=0; for(**var** 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; }
回答4:
First of all why you use 'i' as input to function? we using 'i' to denote running index.. Regarding your question,you want 'a' to be local in your loop so instead of "for(a=0;..." instead write "for(var a=0;"
<html> <body> <script> function NestedArraySummation(arr) { var sum=0; for(var i=0;i<arr.length;i++) { if(typeof arr[i]=="number") sum=sum+arr[i]; else if(arr[i] instanceof Array) sum=sum+NestedArraySummation(arr[i]); } return sum; } var MyArray=[1,[2,3],4,10,[1,2]]; var Sum=NestedArraySummation(MyArray); document.write(Sum); </script> </body> </html>
回答5:
from __builtin__ import int def nestedLists(mylist): sum = 0 if checkIfAllInt(mylist): result = addList(mylist) return result else: for value in mylist: sum = sum + nestedLists(value) return sum def addList(listdata): if(type(listdata) is int): return listdata else: return sum(listdata) def checkIfAllInt(listdata): check = True if(type(listdata) is int): return check else: for value in listdata: if(not type(value) is int): check = False return check return check print nestedLists([1,[2,3,[4,5,[6,7]]]])