变量为什么不清除其值

huangapple go评论73阅读模式
英文:

Why variable doesn't clear its value

问题

以下是翻译好的部分:

为什么以下代码没有删除 secondList 变量的值?

let secondList = list.next.next;
list.next.next = null;

secondList 不应该引用与我们分配 null 的同一个对象吗?

英文:

I have next code:

let list = {
  value: 1,
  next: {
    value: 2,
    next: {
      value: 3,
      next: {
        value: 4,
        next: null
      }
    }
  }
};

Why doesn't the following code delete the value of the secondList variable?

let secondList = list.next.next;
list.next.next = null;

Shouldn't the secondList have reference to the same object to which we assigned null?

答案1

得分: 2

list.next.next的值是对一个对象的引用。

let secondList = list.next.next;将对该对象的引用复制到secondList

list.next.next = null将原始对象的引用替换为null

它不会删除或修改对象本身。secondList的值保持不变。由于仍然存在对对象的引用(在secondList中),因此对象不会被垃圾回收。

英文:

The value of list.next.next is a reference to an object.

let secondList = list.next.next; copies the reference to that object to secondList.

list.next.next = null replaces the original reference to the object with null.

It doesn't delete or modify the object itself. The value of secondList is unchanged. Since there remains a reference to the object (in secondList), the object is not garbage collected.

huangapple
  • 本文由 发表于 2023年1月9日 19:44:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/75056795.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定