使用JavaScript创建LinkedList,但记录实例的方式与预期不同

使用JavaScript创建LinkedList,但记录实例的方式与预期不同,javascript,linked-list,Javascript,Linked List,我正在学习使用JavaScript的LinkedList数据结构。下面是我用Chrome代码片段所做的尝试 (function(){ function LinkedList() { let Node = function(element) { this.element = element; this.next = null; } let head = null;

我正在学习使用JavaScript的LinkedList数据结构。下面是我用Chrome代码片段所做的尝试

(function(){
    function LinkedList() {
        let Node = function(element) {
            this.element = element;
            this.next = null;
        }
    
        let head = null;
    
        this.append = function(element) {
            let node = new Node(element);
            let current;
    
            if (head == null) {
                head = node;
            } else {
                current = head;
                while(current.next){
                    current = current.next;
                }
                current.next = node;
            }
        }
    };

    let l1 = new LinkedList();
    l1.append(3);
    l1.append(4);
    l1.append(2);

    console.log(l1);
})()
基本上,我用append方法创建了一个LinkedList函数,然后创建了一个名为l1的新实例,并向其添加了3个元素。在代码的最后,我希望记录实例l1,它可能类似于

[
{element: 3, next: 4},
{element: 4, next: 2},
{element: 2, next:null},
]
但实际上我得到的是LinkedList函数,而不是新实例

LinkedList {append: ƒ}
append: ƒ (element)

所以我不确定我之间的误解是什么?用JavaScript测试LinkedList的正确方法是什么?谢谢

您可以直接在链接列表上循环以创建数组

(函数(){
函数LinkedList(){
让节点=函数(元素){
this.element=元素;
this.next=null;
}
设head=null;
this.append=函数(元素){
让节点=新节点(元素);
让电流;
if(head==null){
头部=节点;
}否则{
电流=水头;
while(当前.下一个){
当前=当前。下一步;
}
current.next=节点;
}
},
this.toArray=函数(){
var-arr=[];
对于(var curr=head;curr!=null;curr=curr.next)arr.push(curr);
返回arr;
}
};
设l1=新的LinkedList();
l1.追加(3);
l1.追加(4);
l1.追加(2);
console.log(l1.toArray());

})()
这是否回答了您的问题?