值保持返回为未定义

时间:2012-11-05 17:33:50

标签: javascript web prototype

不确定为什么我一直未定义此结果任何帮助都会很棒。结果是假设在开头有x值的数组。感谢

var tester = [1,2,4];
Array.prototype.cons = function(x){
    function reduce(results,y){
        if(y == 1){
            results.unshift(x);
            return results;
        }
        else{
            results.push(this[y-1]);
            y = y-1;
            reduce(results, y);
        }
    }
    return reduce([], this.length);
}
document.getElementById('test').innerHTML = tester.cons(0)

2 个答案:

答案 0 :(得分:0)

您将reduce功能设计为返回结果,但在您的隐形通话中

else{
    results.push(this[y-1]);
    y = y-1;
    reduce(results, y);  // <--- HERE
}

您没有对返回的值执行任何操作(例如将其返回到堆栈中)。这意味着评估继续在您的函数中继续,其底部没有return语句。在JavaScript中,没有return语句意味着函数调用的返回值将是undefined

答案 1 :(得分:0)

如果您只是想将数组中的元素移动到前面,您可以简单地使用它而不是递归遍历数组。

var tester = [1,2,4];
Array.prototype.cons = function(x){
    // Copy the array. This only works with simple vars, not objects
    var newArray = this.slice(0);        

    // Check to make sure the element you want to move is in the array
    if (x < this.length) {
        // Remove it from the array
        var element = newArray.splice(x, 1);
        // Add to the beginning of the array
        newArray.unshift(element);
    }
    return newArray;
}
document.getElementById('test').innerHTML = tester.cons(4)​;​

编辑:制作数组的副本

相关问题