首页 > 解决方案 > javascript - 未清除数组引用

问题描述

当我分配 anotherArrayList = arrayList 时,anotherArrayList 是指向 arrayList 的指针。那么为什么当我清空arrayList 时这不起作用。

var arrayList = ['a', 'b', 'c', 'd', 'e', 'f']; 
var anotherArrayList = arrayList;  

arrayList[1] = '15';

console.log(arrayList); // output: [ "a", "15", "c", "d", "e", "f" ]
console.log(anotherArrayList); // output: [ "a", "15", "c", "d", "e", "f" ]

arrayList = []; 
console.log(arrayList); // output: []
console.log(anotherArrayList); // output: [ "a", "15", "c", "d", "e", "f" ] 

标签: javascript

解决方案


通过分配一个新数组,旧对象引用获得对空数组的新引用。

您也可以将零分配给length清空对象引用的属性。

var arrayList = ['a', 'b', 'c', 'd', 'e', 'f'],
    anotherArrayList = arrayList;

arrayList[1] = '15';

console.log(arrayList);        // [ "a", "15", "c", "d", "e", "f" ]
console.log(anotherArrayList); // [ "a", "15", "c", "d", "e", "f" ]

arrayList.length = 0; 
console.log(arrayList);        // []
console.log(anotherArrayList); // [] 


推荐阅读