如何在JavaScript中清空数组? [重复]

问题描述 投票:3回答:2

这个问题在这里已有答案:

我使用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']

方法2

let Method2 = ArrayList;  // Referenced arrayList by another variable 
ArrayList.length = 0; // Empty the array by setting length to 0
console.log(Method2 ); // Output []
javascript arrays arraylist ecmascript-6
2个回答
1
投票

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 []

1
投票

理解这里发生的事情的技巧是理解变量在JavaScript中的工作方式以及赋值(=)运算符的作用。

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

当我们通过=运算符为变量赋值时,我们只更改变量所指向的内容,我们不会更改现有内存位置的实际数据,我们只是让变量不再指向它。

// 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 []
© www.soinside.com 2019 - 2024. All rights reserved.