繁体   English   中英

值不断返回未定义

[英]Value keeps returning as undefined

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

您设计了reduce函数以返回结果,但是在它的追溯调用中

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

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

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

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)​;​

编辑:制作数组的副本

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM