【发布时间】: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,它详细解释了你在说什么。