我的灵感来自 this question在 JavaScript 中编写递归函数以添加数组元素并相应地返回数组。
伪代码
arr = [1,2,3,4,5,6]
func (arr,2) = > [1+3+5, 2+4+6]
[9,12]
func (arr,3) = > [1+4,2+5,3+6]
[5,7,9]
所以我写了一个 fiddle ,here .
var input = [1,2,3,4,5,6,7,8,9];
function tupleAdd(tuple,i,p,t,output){
if(typeof t == "undefined")
t=0;
if(typeof p == "undefined")
p=0;
if(typeof output == "undefined")
output = [];
if(typeof output[t] =="undefined")
output[t]=0;
output[t]+=i[p];
p++;
t++;
t>=tuple?t=0:null;
if(p<i.length)
tupleAdd(tuple,i,p,t,output);
else{
console.log(output);
return(output);
}
}
x = tupleAdd(3,input);
console.log(x);
我的函数有效,因为第一个 console.log()
显示了适当的值。让我感到奇怪的是,当我return
output
(带或不带括号),并尝试再次记录它时,我得到了undefined
。
我觉得这非常令人不安。谁能阐明为什么 return
值与 console.log
值不同?
最佳答案
你的递归被破坏了。你变得不确定,因为你没有对内部函数调用的返回。
tupleAdd(tuple,i,p,t,output);
需要
return tupleAdd(tuple,i,p,t,output);
关于javascript - 在 JavaScript 中返回一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19989955/