简体   繁体   中英

Why isn't this recursion working on Javascript?

The problem is in the listToArray function, arrayToList just there to provide context on how lists are being created.

var arrayToList = function (array) {
    var lastList = null;
    for (i=array.length-1; i >= 0; i--) {
        var list = {value : array[i], rest : lastList};
        lastList = list;
    }
    return lastList;
}

var list = arrayToList([1,2,3])

var listToArray = function (list) {
    var array = [];
    array.push(list.value);
    if (list.rest != null) {
        array.concat(listToArray(list.rest));
    } else {
        return array;
    }
}

var array = listToArray(list)

> list
{ value: 1, rest: { value: 2, rest: { value: 3, rest: null } } }
> array
undefined

Couple of fixes :

  • Have to return the array to be used in array.concat
  • Every time a new arr = [] loses the context of the previous. Either it should be passed as a parameter, or keeping it in a global context.

Run the following snippet.

 var arrayToList = function(array) { var lastList = null; for (i = array.length - 1; i >= 0; i--) { var list = { value: array[i], rest: lastList }; lastList = list; } return lastList; } var list = arrayToList([1, 2, 3]) var listToArray = function(list, array) { if (!array) { array = []; } array.push(list.value); if (list.rest != null) { array.concat(listToArray(list.rest, array)); } else { return array; } // need to return the array which is used in array.concat return array; } var array = listToArray(list); console.log(list); console.log(array); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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