【问题标题】:Mutation in javascript?javascript中的突变?
【发布时间】: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() 方法中因为使用了变量节点突变没有发生为什么会这样?

标签: javascript linked-list


【解决方案1】:

在 size2() 中,您不会改变 this.head 因为您首先将引用复制到局部变量中。因为在while loop 中,您正在改变本地node = node.next,从这里开始node 和this.head 不再链接。这是永恒的价值/参考 这是一篇关于它的 javascript https://codeburst.io/explaining-value-vs-reference-in-javascript-647a975e12a0

文章

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多