【问题标题】:javascript - array reference is not clearedjavascript - 未清除数组引用
【发布时间】:2019-07-14 03:08:21
【问题描述】:

当我分配 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


【解决方案1】:

数组和对象在 javascript 中是 非原始 数据类型。当一个变量被分配到一个非原始数据类型的引用时,内存位置的副本存储在那个新变量中。

【讨论】:

    【解决方案2】:

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

    您可以将零分配给 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); // [] 

    【讨论】:

    • 这不能回答他的问题。
    【解决方案3】:

    它不会清空你的另一个数组,因为你实际上并没有清除/清空它,而是在内存中创建一个 new 空数组,arrayList 将指向它,而 @ 987654322@ 仍将指向整个数组。

    相反,要清空数组本身,您可以使用.length 属性: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: []

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-18
      • 2021-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-24
      • 2021-12-17
      • 2016-07-03
      相关资源
      最近更新 更多