【发布时间】:2018-06-05 17:13:01
【问题描述】:
在下面的代码中 size2() 方法工作正常。但在 size1() 中,它正在改变对象并使其为 null。为什么在 size2() 中没有发生这种行为?
class Node {
constructor(data, next = null) {
this.data = data;
this.next = next;
}
}
class LinkedList {
constructor() {
this.head = null;
}
insert(data) {
this.head = new Node(data, this.head);
}
size1() {
var counter = 0;
while (this.head) {
counter++;
this.head = this.head.next;
}
return counter;
}
size2() {
var counter = 0;
var node = this.head;
while (node) {
counter++;
node = node.next;
}
return counter;
}
}
var list = new LinkedList();
list.insert(35);
console.log(list);
console.log(list.size2());
对我来说,这两种方法看起来都一样,但这些方法有什么细微的不同吗?
【问题讨论】:
-
它是因为当你调用 size2 时它的下一个因此为 null
-
在 size2() 方法中因为使用了变量节点突变没有发生为什么会这样?