JavaScript 数组可以清空的方法有多种:1. 将 length 设置为 0;2. 使用 splice() 删除整个数组;3. 使用 while 循环逐个删除元素;4. 使用 fill() 替换所有元素为 null;5. 重新分配一个空数组。

如何清空 JavaScript 数组
清空 JavaScript 数组的方法有几种:
1. length = 0
<code class="javascript">const arr = [1, 2, 3]; arr.length = 0; console.log(arr); // []</code>
2. splice(0, arr.length)
<code class="javascript">const arr = [1, 2, 3]; arr.splice(0, arr.length); console.log(arr); // []</code>
3. while 循环
<code class="javascript">const arr = [1, 2, 3];
while (arr.length > 0) {
arr.pop();
}
console.log(arr); // []</code>4. fill(null, 0, arr.length)
<code class="javascript">const arr = [1, 2, 3]; arr.fill(null, 0, arr.length); console.log(arr); // [null, null, null]</code>
5. 重新分配一个空数组
<code class="javascript">const arr = [1, 2, 3]; arr = []; console.log(arr); // []</code>
注意:
- 第 1 种方法将数组的长度设置为 0,而其他方法会删除整个数组。
- 第 4 种方法会将数组中的元素替换为
null,但数组的长度保持不变。 - 第 5 种方法是最简单的方法,但会创建一个新的数组对象,并不修改原始数组。










