这个问题已经在这里有了答案: > How do I empty an array in JavaScript? 18个
我正在使用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','f']
方法二
let Method2 = ArrayList; // Referenced arrayList by another variable
ArrayList.length = 0; // Empty the array by setting length to 0
console.log(Method2 ); // Output []
最佳答案
ArrayList在第一个方法之后被清空,因此您正在向Method2分配一个空数组
let ArrayList = ['a','f'];
let Method1 = ArrayList; // Referenced arrayList by another variable
ArrayList = []; // Empty the array
console.log(Method1); // Output ['a','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 []