List data structures in JavaScript

前端 未结 3 1545
天涯浪人
天涯浪人 2020-11-30 14:57

In an exercise in the book Eloquent JavaScript I need to create a list data structure (as below) based on the array [1, 2, 3].

The tutorial JavaScript

3条回答
  •  执念已碎
    2020-11-30 15:35

    This tutorial shows how to do this but I don't really understand the intention to create this.start and this.end variables inside the tutorial.

    The tutorial uses a List wrapper around that recursive structure with some helper methods. It says: "It is possible to avoid having to record the end of the list by performing a traverse of the entire list each time you need to access the end - but in most cases storing a reference to the end of the list is more economical."

    This code gives me an infinite loop of array[0].

    Not really, but it creates a circular reference with the line list.rest = list;. Probably the code that is outputting your list chokes on that.

    What's wrong is with my code?

    You need to create multiple objects, define the object literal inside the loop body instead of assigning to the very same object over and over! Also, you should access array[i] inside the loop instead of array[0] only:

    function arrayToList(array){
        var list = null;
        for (var i=array.length-1; i>=0; i--)
            list = {value: array[i], rest:list};
        return list;
    }
    

提交回复
热议问题