var arr = [{id: 1, name: 'John'}, {id: 2, name: 'Mike'}];
var member = arr[0];
arr.splice(0, 1);
console.log(member);
答案 0 :(得分:10)
您可以继续访问它,因为您仍然对其具有引用。它不再存在于数组中,但仍然存在。它会一直存在,直到所有对它的引用都被删除为止,并且一旦存在,就可以进行垃圾回收了。
之后:
var arr = [{id: 1, name: 'John'}, {id: 2, name: 'Mike'}];
您的内存中有类似的内容(省略了一些详细信息):
+−−−−−−−−−−−−+ arr:Ref4875−−−−−−>| (array) | +−−−−−−−−−−−−+ +−−−−−−−−−−−−−−+ | 0: Ref8612 |−−−−−>| (object) | | 1: Ref4631 |−−+ +−−−−−−−−−−−−−−+ +−−−−−−−−−−−−+ | | id: 1 | | | name: "John" | | +−−−−−−−−−−−−−−+ | | +−−−−−−−−−−−−−−+ +−−>| (object) | +−−−−−−−−−−−−−−+ | id: 1 | | name: "John" | +−−−−−−−−−−−−−−+
(“ Ref1234”值称为对象引用。您永远不会看到它们的实际值,但是可以将它们视为JavaScript引擎用来查找对象在内存中的位置的数字)
此后:
var member = arr[0];
member
和数组均引用对象,如下所示:
member:Ref8612−−−−−−−−−−−−−−−−−−−−−+ +−−−−−−−−−−−−+ | arr:Ref4875−−−−−−>| (array) | | +−−−−−−−−−−−−+ | +−−−−−−−−−−−−−−+ | 0: Ref8612 |−−−+−>| (object) | | 1: Ref4631 |−−+ +−−−−−−−−−−−−−−+ +−−−−−−−−−−−−+ | | id: 1 | | | name: "John" | | +−−−−−−−−−−−−−−+ | | +−−−−−−−−−−−−−−+ +−−>| (object) | +−−−−−−−−−−−−−−+ | id: 1 | | name: "John" | +−−−−−−−−−−−−−−+
之后:
arr.splice(0, 1);
该数组不再有对其的引用,但是member
仍然有:
+−−−−−−−−−−−−−−+ member:Ref8612−−−−−−−−−−−−−−−−−−−−−−−>| (object) | +−−−−−−−−−−−−+ +−−−−−−−−−−−−−−+ arr:Ref4875−−−−−−>| (array) | | id: 1 | +−−−−−−−−−−−−+ | name: "John" | | 0: Ref4631 |−−+ +−−−−−−−−−−−−−−+ +−−−−−−−−−−−−+ | | | | | | +−−−−−−−−−−−−−−+ +−−>| (object) | +−−−−−−−−−−−−−−+ | id: 1 | | name: "John" | +−−−−−−−−−−−−−−+