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.
Can anyone explain this answer without any jargon? I can only learn by instructions.
Here is what I came up with for arrayToList: So start list null, create for loop decrementing and inside define "i" then return list.
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;
}
what is rest:list
inside the list
object?
The last comment by @eloquent need to be modified:
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) );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With