Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
158 views
in Technique[技术] by (71.8m points)

List data structures in JavaScript

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 Data Structures - The Linked List shows how to do this, but I don't really understand the intention to create this.start and this.end variables inside the tutorial.

var list = {
  value: 1,
   rest: {
     value: 2,
      rest: {
        value: 3,
        rest: null
      }
   }
};

I tried to solve this via the code below.

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

This code gives me an infinite loop of array[0]. What's wrong with my code?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...