我正在使用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 []
答案 0 :(得分: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 :(得分: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 []