如何在JavaScript中清空数组?

前端之家收集整理的这篇文章主要介绍了如何在JavaScript中清空数组? 前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

这个问题已经在这里有了答案:            >            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 []
原文链接:https://www.f2er.com/js/531131.html

猜你在找的JavaScript相关文章