简体   繁体   English

值不断返回未定义

[英]Value keeps returning as undefined

Not sure why i keep getting undefined for this results any help would be great. 不知道为什么我会一直对此结果保持不确定,任何帮助都会很棒。 The result is suppose to the the array with the x value at the beginning. 结果假定为以x值开头的数组。 thanks 谢谢

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)

You designed your reduce function to return results, but in your recusive call of it 您设计了reduce函数以返回结果,但是在它的追溯调用中

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

You aren't doing anything with the returned value (such as returning it up the stack). 您不会对返回的值做任何事情(例如将其返回堆栈)。 This means that evaluation continues down your function, at the bottom of which there is no return statement. 这意味着评估将继续执行您的功能,在该功能的底部没有return语句。 In JavaScript, no return statement means that the return value of the function call will be undefined 在JavaScript中,没有return语句意味着函数调用的返回值是undefined

If you're just trying to move an element in the array to the front, you can simply use this instead of recursively going through the array. 如果您只是想将数组中的元素移到最前面,则可以简单地使用它,而不是递归地遍历数组。

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

EDIT: Made a copy of the array 编辑:制作数组的副本

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

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