Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/393.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/extjs/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何从链表显示到控制台节点_Javascript_Debugging_Linked List_Nodes_Console.log - Fatal编程技术网

Javascript 如何从链表显示到控制台节点

Javascript 如何从链表显示到控制台节点,javascript,debugging,linked-list,nodes,console.log,Javascript,Debugging,Linked List,Nodes,Console.log,我有一个创建链接列表的类,还有一个向该列表添加节点的函数。我试图对列表实现更多函数,但我希望通过显示整个列表来查看这些函数所做的更改 代码如下: function LinkedList() { var length = 0; var head = null; var Node = function(element) { this.element = element; this.next = null; }; this.size = function() {

我有一个创建链接列表的类,还有一个向该列表添加节点的函数。我试图对列表实现更多函数,但我希望通过显示整个列表来查看这些函数所做的更改

代码如下:

function LinkedList() {
  var length = 0;
  var head = null;

  var Node = function(element) {
    this.element = element;
    this.next = null;
  };

  this.size = function() {
    return length;
  };

  this.head = function() {
    return head;
  };

  this.add = function(element) {
    var node = new Node(element);
    if (head === null) {
      head = node;
    } else {
      var currentNode = head;

      while (currentNode.next) {
        currentNode = currentNode.next;
      }

      currentNode.next = node;
    }
    length++;
  };

声明LinkedList类并使用class.add(element)函数添加元素后,如何使用console.log()显示整个列表?

您需要编写LinkedList类的
toString
方法。请参阅:

您可以在
prototype
对象中定义方法
toString
,并循环所有项

函数链接列表(){
变量长度=0;
var头=空;
变量节点=函数(元素){
this.element=元素;
this.next=null;
};
this.size=函数(){
返回长度;
};
this.head=函数(){
回流头;
};
this.add=函数(元素){
var节点=新节点(元素);
if(head==null){
头部=节点;
}否则{
var currentNode=头部;
while(currentNode.next){
currentNode=currentNode.next;
}
currentNode.next=节点;
}
长度++;
};
}
LinkedList.prototype.toString=函数(){
设head=this.head();
让结果=[];
while(head){
结果.推(头.元件);
console.log();
head=head.next;
}
返回结果。join(“,”);
}
let list=new LinkedList();
列表。添加(“测试”);
列表。添加(“测试2”);
列表。添加(“测试3”);
log(list.toString())