3

我受到这个问题的启发,在 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

4

3 回答 3

3

你的递归被打破了。由于内部的函数调用没有返回值,因此您变得未定义。

tupleAdd(tuple,i,p,t,output);

需要是

return tupleAdd(tuple,i,p,t,output);
于 2013-11-14T22:44:16.997 回答
2

您需要返回递归调用的值:

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)
        return tupleAdd(tuple,i,p,t,output);
    else{
        console.log(output);
        return(output);
    }
}

x = tupleAdd(3,input);
console.log(x);
于 2013-11-14T22:44:20.677 回答
-2
function doTuple(arr, tuple){

    if(!arr.length){
        return tuple;
    }

    var el = arr.splice(0,1);

    el % 2 ? tuple.evens += +el : tuple.ods += +el;

    return doTuple(arr, tuple);
}

console.log(doTuple([1,2,3,4,5], {evens:0,ods:0}));
于 2013-11-14T22:54:25.577 回答