问题在于listToArray函数,arrayToList就是为了提供有关如何创建列表的上下文。
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
答案 0 :(得分:1)
一些修复:
array.concat
arr = []
丢失前一个的上下文。它应该作为参数传递,或者将其保存在全局上下文中。运行以下代码段。
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);