列出JavaScript中的数据结构 [英] List data structures in JavaScript

查看:117
本文介绍了列出JavaScript中的数据结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

练习中=http://eloquentjavascript.net/ =nofollow> Eloquent JavaScript 我需要根据数组[1,2,3]创建一个列表数据结构(如下所示) 。

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].

教程 JavaScript数据结构 - 链接列表 显示了如何执行此操作,但我真的不明白创建 this.start 和 this.end 教程中的变量。

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

这段代码给了我一个无限循环的数组[0]。我的代码出了什么问题?

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

推荐答案


这个教程展示了如何做到这一点,但我真的不明白打算在教程中创建 this.start this.end 变量。

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.

本教程使用带有一些辅助方法的递归结构的 List 包装器。它说:每次你需要访问结尾时,通过遍历整个列表,可以避免必须记录列表的 end - 但在大多数情况下,存储对列表末尾的引用更为经济。

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."


此代码给了我无限的数组循环[0]。

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

不是真的,但是它创建了一个带有行的循环引用。 rest = list; 。可能输出你的列表的代码就是choke。

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?

您需要创建多个对象,在循环体内定义对象文字,而不是一遍又一遍地分配给同一个对象!此外,您应该在循环内访问 array [i] 而不是 array [0]

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

这篇关于列出JavaScript中的数据结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆