0

不知道为什么我对这个结果一直不确定,任何帮助都会很棒。结果假设为以 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)
4

2 回答 2

0

你设计了你的reduce函数来返回结果,但是在你对它的递归调用中

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

您没有对返回的值做任何事情(例如将其返回堆栈)。这意味着评估会继续您的功能,在其底部没有return声明。在 JavaScript 中,没有 return 语句意味着函数调用的返回值将是undefined

于 2012-11-05T17:44:18.183 回答
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)​;​

编辑:制作了数组的副本

于 2012-11-05T17:47:49.713 回答