我制作了这个代码,将数组转换为
下面的列表// This is a function to make a list from an array
// This is a recursive function
function arrayToList(array) {
// I use an object constructor notation here
var list = new Object();
// This is to end the recursion, if array.length == 1, the function won't call itself and instead
// Just give rest = null
if (array.length == 1) {
list.value = array[array.length - 1];
list.rest = null;
return list;
} else {
// This is to continue the recursion. If the array.length is not == 1, make the rest key to call arrayToList function
list.value = array[0];
// To avoid repetition, splice the array to make it smaller
array.splice(0,1);
list.rest = arrayToList(array);
return list;
}
}
arrayToList([1, 2]);
但是,现在我正在尝试颠倒这个过程,即编写一个从列表中返回数组的函数。
所以我希望功能如下所示
listToArray(function(arrayToList([1,2])
=> [1,2]
我该怎么做,请帮帮忙?
答案 0 :(得分:3)
以下是代码:
function listToArray(list) {
var array = [];
var item = list;
while (item) {
array.push(item.value);
item = item.rest;
}
return array;
}
答案 1 :(得分:0)
很抱歉发布完整代码,但我这样做是为了便于理解:
function arrayToList(arr) {
var li = {};
li.value=arr[0], arr.shift();
if(arr.length) li.rest=arrayToList(arr);
else li.rest=null;
return li;
}
function listToArray(li) {
var arr = [];
for(var i=li; i; i=i.rest) arr.push(i.value);
return arr;
}
function prepend(a, b) {
var li = {};
li.value=a, li.rest=b;
return li;
}
function nth(li, n) {
var elem, cnt=0;
for(var i=li; i; i=i.rest, cnt++) {
if(cnt==n) {
elem=i.value;
break;
}
}
return elem;
}
console.log(arrayToList([10, 20]));
// → {value: 10, rest: {value: 20, rest: null}}
console.log(listToArray(arrayToList([10, 20, 30])));
// → [10, 20, 30]
console.log(prepend(10, prepend(20, null)));
// → {value: 10, rest: {value: 20, rest: null}}
console.log(nth(arrayToList([10, 20, 30]), 1));
// → 20