javascript - javascript中的突变?

标签 javascript linked-list this

在下面的代码中,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() 中,您没有改变 this.head,因为您首先将引用复制到局部变量中。因为在 while 循环中,您正在改变本地 node = node.next 从这里开始 nodethis.head不再链接。这是永恒的值/引用陷阱

这是一个related article .

关于javascript - javascript中的突变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50705565/

相关文章:

javascript - 使用 TypeScript 自定义 knockout 验证规则

c++ - "this"的值什么时候偏移了一个偏移量?

javascript - 使用 JavaScript 时禁用 Safari 消息

javascript - 如果语句不起作用,可能是一些基本问题

javascript - 数字格式问题

LinkedLists 中的 Java LinkedLists - 访问项目

javascript - 在 jQuery 方法中访问对象文字的属性

javascript - 获取 CouchDB 附件并将其显示在 html 页面上

algorithm - 链表的简单排序

java - 如何使用java导出文件中的数据