代码之家  ›  专栏  ›  技术社区  ›  Manoj Bhardwaj

如何在JavaScript中清空数组?[副本]

  •  3
  • Manoj Bhardwaj  · 技术社区  · 6 年前

    我用ArrayList作为数组,

    let ArrayList   =  ['a','b','c','d','e','f'];
    

    我混淆了方法1和方法2,因为在这两种情况下,我引用了另一个ArrayList,您还可以通过这个链接检查日志 https://jsfiddle.net/mnjsnj/u1fms8wx/2/

    方法1

    let Method1 = ArrayList;  // Referenced arrayList by another variable 
    ArrayList= []; // Empty the array 
    console.log(Method1); // Output ['a','b','c','d','e','f']
    

    let Method2 = ArrayList;  // Referenced arrayList by another variable 
    ArrayList.length = 0; // Empty the array by setting length to 0
    console.log(Method2 ); // Output []
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   brk    6 年前

    ArrayList 在第一个方法之后被清空,因此将空数组分配给 Method2

    let ArrayList = ['a', 'b', 'c', 'd', 'e', 'f'];
    
    let Method1 = ArrayList; // Referenced arrayList by another variable 
    ArrayList = []; // Empty the array 
    console.log(Method1); // Output ['a','b','c','d','e','f']
    
    console.log('ArrayList after Method1....!' , ArrayList)
    // here an empty array is assinged to Method2
    let Method2 = ArrayList; // Referenced arrayList by another variable 
    ArrayList.length = 0; // Empty the array by setting length to 0
    console.log(Method2); // Output []
        2
  •  1
  •   nem035    6 年前

    = )接线员知道。

    变量只是内存位置的绑定名称。

    当我们通过 运算符,我们只改变变量指向的对象,我们不改变现有内存位置的实际数据,我们只是使变量不再指向它。

    // Method1 now points to the same memory location as ArrayList
    let Method1 = ArrayList;
    // ArrayList variable now points to a new memory location containing an empty array
    ArrayList = []; 
    // Method1 is still pointing to the original memory location so the array is unaffected
    console.log(Method1);
    

    在第二个示例中,直接影响 ArrayList 是指通过改变 length 0

    // point Method2 variable to the same location as ArrayList variable
    let Method2 = ArrayList; 
    // change the data stored at the location ArrayList is pointing to
    ArrayList.length = 0; // Empty the array by setting length to 0
    // Since Method2 is also pointing to that location, we see the empty array
    console.log(Method2); // Output []