我将对象引用存储在我的 JavaScript 集中:
let set1 = new Set();
let obj = {};
然后,如果我使用 has() 方法和 Set 对象的 size 属性,我会得到下一个结果:
console.log(set1.size) //it returns 1
console.log(set1.has(obj)) //it returns true
但是,如果我使用下一个代码删除对象的引用:
obj = null;
然后奇怪的行为发生在我身上:
console.log(set1.size); //it returns 1 because they are Hard Sets.
console.log(set1.has(obj)); //it returns false
在最后一行,如果大小没有改变,为什么会返回false?然后引用丢失但大小没有改变。
最佳答案
In the last line, why does it return false if the size is not changed?
它返回 size = 1
因为它仍然保留一个值(对该对象的引用)。
它返回 false
,因为它没有等于 null
的值。
But, if I remove the reference of the object using the next code:
您只需覆盖变量的值。在那之后,仍然有一个对该对象的引用(在 Set 内)。
要从 Set
中删除元素,您需要使用 Set.prototype.delete()
方法:
set1.delete(obj);
大概您需要在 obj
仍然持有对该对象的引用时执行此操作。
关于JavaScript 设置丢失的引用但不改变大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37087440/