function arrayToList(array){
LIST = {};
function add(list, index){
if(index < array.length){
list = {value:array[index], rest : null};
add(list.rest, index+1);
}
}
add(LIST,0);
return LIST;
}
Run Code Online (Sandbox Code Playgroud)
您的代码就像JavaScript是一种传递引用语言一样编写.它不是.
具体来说,在您的add()函数内部,您的代码被编写为好像对参数赋值list将影响作为参数传递给函数的内容; 它不会.也就是说,这句话:
list = {value:array[index], rest : null};
Run Code Online (Sandbox Code Playgroud)
将修改参数的值,但不会影响全局变量LIST.
您可以通过不同的方式重新设计代码.这是一种方式:
function arrayToList(array){
function add(index){
var entry = null;
if (index < array.length) {
entry = { value: array[index], rest: add(index + 1) };
}
return entry;
}
return add(0);
}
Run Code Online (Sandbox Code Playgroud)