我受到这个问题的启发,在 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]
所以我在这里写了一个小提琴。
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?