【问题标题】:Linked List delete deletes node before console.log in javascript链接列表删除在javascript中的console.log之前删除节点
【发布时间】:2017-02-10 14:09:25
【问题描述】:

所以,我在 js 中创建了一个标准的链表类,它运行良好,但例如 /.....

     var myRef = new LinkedList()  //let's say with vals 1->2->3   
     console.log(myRef) //2->3  They are both the same!!!! even though delete happens later in code!!!
     myRef.deleteFirst();

    console.log(myRef)  //2->3 They are both the Same!! 

    LinkedList.prototype.deleteFirst = function() {
       if (this.head.next == null) {
       return;
  }
  var dummy = this.head.next.next;
  var value = this.head.next.data;
  delete this.head.next;
  this.head.next = dummy;
  this.head.length -= 1;

  return value;

}

【问题讨论】:

标签: javascript data-structures linked-list prototype this


【解决方案1】:

控制台会有一个对象的引用,当对象更新时会更新。你可以这样做:

console.log(jQuery.extend(true, {}, myRef));

这将创建您对象的独立副本。这将允许您检查不同的状态。

【讨论】:

  • jQuery 在浏览器中默认不可用。
  • true,您需要包含它(例如,通过将其放入您的 HTML:<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
【解决方案2】:

试试这个:

console.log(JSON.stringify(myRef));

这将打印对象的字符串化版本。所以不是你的对象会得到对象的内容,否则因为 myRef 是一个指针,它的内容会改变并且日志显示最新的值。

【讨论】:

    猜你喜欢
    • 2015-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-31
    • 2015-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多