简体   繁体   English

javascript 中的突变?

[英]Mutation in javascript?

In the below code size2() method working fine.But in size1() it is mutating the object and making it null.why such behavior is not happening in size2() ?在下面的代码size2()方法中工作正常。但在 size1 size1()中,它正在改变 object 并使其成为 null。为什么这种行为在 size2 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());

To me both the method looks same.对我来说,这两种方法看起来都一样。 Is there any subtle difference in those methods?这些方法有什么细微的区别吗?

In size2() , you are not mutating this.head because you first copy the reference in a local variable.size2()中,您不会改变this.head ,因为您首先将引用复制到局部变量中。 Since in the while loop you are mutating the local node = node.next starting here node and this.head are not linked any more.由于在while循环中,您正在改变本地node = node.next从这里开始nodethis.head不再链接。 It's the eternal Value/Reference pitfall .这是永恒的价值/参考陷阱

Here is a related article .这是一篇相关文章

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM