简体   繁体   中英

javascript - array reference is not cleared

When I assign anotherArrayList = arrayList, anotherArrayList is a pointer to arrayList. So why this does not work when I empty the 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" ] 

By assigning a new array, the old object reference gets a new reference to the empty array.

You could assign zero to the length property which empties the object reference as well.

 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); // [] 

It doesn't empty your other array because you're not actually clearing/emptying it, instead you are creating a new empty array in memory, which arrayList will point to, whereas anotherArrayList will still point to the full array.

Instead, to empty the array itself, you can use the .length property: arrayList.length = 0

 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.length = 0; console.log(arrayList); // output: [] console.log(anotherArrayList); // output: [] 

Array and objects are non-primitive data-type in javascript. When a variable is assigned with reference to a non-primitive data-type, the copy of memory location is stored in that new variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM