Question from eloquentjavascript :
Write a function arrayToList that builds up a data structure like the previous one when given [1, 2, 3] as argument, and write a listToArray function that produces an array from a list. Also write the helper functions prepend, which takes an element and a list and creates a new list that adds the element to the front of the input list, and nth, which takes a list and a number and returns the element at the given position in the list, or undefined when there is no such element.
谁能不用行话解释这个答案? 我只能按照说明学习。
这是我为 arrayToList 想出的: 所以开始列表 null,创建 for 循环递减并在内部定义“i”然后返回列表。
function arrayToList(array){ //pass list as parameter
var list = null; // don't know why we make it null
for (var i=array.length-1; i>=0; i--) // why -1 on the length?
list = {value: array[i], rest:list}; //clueless
return list;
}
list
对象中的rest:list
是什么?
最佳答案
@eloquent 的最后一条评论需要修改:
var arr1 = [10, 20, 30];
function arrayToList(arr) {
var list = {};
for (var i = 0; i < arr.length; i++) {
list.value = arr.splice(0, 1)[0];
list.rest = (arr.length > 0) ? arrayToList(arr) : null;
}
return list;
}
console.clear();
console.log( arrayToList(arr1) );
关于javascript - Eloquent Javascript 第 4 章 : arrayToList/listToArray Execise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28800442/