【问题标题】:How does editing variable inside a class function works?在类函数中编辑变量如何工作?
【发布时间】:2020-12-07 13:40:03
【问题描述】:

我偶然发现了这段代码,它应该删除链表的最后一个元素。 我不明白如何通过修改局部变量来修改类属性:

class LinkedList {
  constructor() {
    this.head = null;
  }
  removeLast() {
    if (!this.head) {
      return;
    }

    if (!this.head.next) {
      this.head = null;
      return;
    }

    let previous = this.head;
    let node = this.head.next;
    while (node.next) {
      previous = node;
      node = node.next;
    }
    previous.next = null;
  }
}

有任何解释或链接可以更好地理解这个主题吗? 谢谢。

【问题讨论】:

  • 代码中的所有局部变量似乎都引用了一个对象,因此您可以通过存储在这些局部变量中的引用来修改对象的属性。
  • 谢谢我找到了这个链接link,它详细解释了你在说什么。

标签: javascript linked-list


【解决方案1】:

您问题中的代码修改了对象引用。

与原始值不同,两个变量可以引用同一个对象。因此,使用任何对象引用修改对象都会修改实际对象,并且更改将反映在所有对象引用中。

示例:

下面的代码 sn -p 显示一个例子:

const obj = { name: 'John' };
const obj2 = obj;

obj2.name = 'Mike';

console.log(obj);

在上面的代码示例中,obj2.name 已更改,但当 obj 记录在最后一行时,name 属性的值更改为“Mike”。这是因为objobj2 都指向内存中完全相同的对象

要理解您问题中的代码,您需要牢记上述代码示例并了解其工作原理。

以下是解释removeLast() 方法如何工作的步骤:

  1. 检查列表是否为空。如果是,则从函数中返回,因为没有要删除的内容。

    if (!this.head) {
       return;
    }
    
  2. 如果链表中只有一个节点,则使head指向null,然后从函数中返回。

    if (!this.head.next) {
       this.head = null;
       return;
    }
    
  3. 现在,我们需要遍历链表,到达链表中倒数第二个节点。当我们到达倒数第二个节点时,我们可以将倒数第二个节点的next 指向null。这将删除对最后一个节点的任何引用。

    // create a temporary pointer to the first node 
    // in the linked list       
    let previous = this.head;
    
    // create a temporary pointer to the second node
    // in the linkedlist. "this.head.next" could be "null"
    // if there's only 1 node in the linkedlist 
    let node = this.head.next;
    
    // traverse the linkedlist until "node.next" is not "null"
    while (node.next) { 
       // point "previous" to the node that is pointed
       // to by "node" variable
       previous = node;
    
       // update "node" variable to point the node that
       // is next to the node that is currently pointed to by "node"
       // variable
       node = node.next;
    }
    
  4. 在第三步之后,previous 将指向链表中倒数第二个节点。最后,倒数第二个节点的next 设置为null。这样做会删除最后一个节点。

    previous.next = null;
    

【讨论】:

  • 感谢您对对象引用的精确性,这就是我所缺少的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-22
  • 2020-03-31
相关资源
最近更新 更多