任何人都可以帮我弄清楚我在代码中做错了什么吗? 因为我想创建一个函数,它可以帮助我将所有数组数据转换成列表并打印出列表。
原始说明 ****编写一个函数arrayToList,当给定[1,2,3]作为参数时,构建一个类似于前一个的数据结构,并编写一个listToArray函数,从列表中生成一个数组。还要编写辅助函数prepend,它接受一个元素和一个列表,并创建一个新的列表,将元素添加到输入列表的前面,nth,它接受一个列表和一个数字,并返回给定位置的元素。列表,或没有这样的元素时未定义。 如果你还没有,也写一个递归版本的第n。****
function arrayToList(arrayx){
for(var i=10;i<arrayx.length;i+=10)
var list = {
value: i,
rest: {
value: i+=10,
rest: null}}
return list;
}
我想要的结果是
console.log(arrayToList([10, 20]));
// → {value: 10, rest: {value: 20, rest: null}}
答案 0 :(得分:2)
你也可以试试这个:
function arrayToList(arrayx){
for(var i = arrayx[0];i < Math.max.apply(Math,arrayx); i+=arrayx[0])
{
var list = {
value: i,
rest: {
value: i+=10,
rest: null
}
}
return list;
}
}
console.log(arrayToList([10 , 20]));
答案 1 :(得分:0)
// 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;
}
}
console.log(arrayToList([10, 20]));