如何在 JavaScript 中清空数组
要清空数组,需要调用 splice()
方法,将 0 作为参数传递给它 - splice(0)
。 该方法将通过删除并返回从索引零开始的所有元素来清空原始数组。
const arr = ['a', 'b', 'c'];
arr.splice(0);
console.log(arr); // 👉️ []
我们传递给 Array.splice
方法的参数是起始索引 - 我们开始更改数组的索引。
splice
方法采用的第二个参数是 delete count
- 应该从数组中删除的元素数,从起始索引开始。
如果未提供删除 delete count
,则从起始索引开始的所有元素都将被删除。
出于我们的目的,我们提供了一个 0 的起始索引来删除所有元素并清空数组。
一个更高效和更好的解决方案是重新分配保存数组的变量。
要清空数组,请重新分配存储数组的变量并将其设置为空数组,例如 arr = []
。 请注意,我们只能重新分配使用 let
和 var
关键字声明的变量。 这是在 JavaScript 中清空数组的最高效方式。
let arr = ['a', 'b', 'c'];
arr = [];
console.log(arr); // 👉️ []
请注意,我们使用 let
关键字来声明 arr 变量。 如果我们使用 const
关键字,我们将无法重新分配变量并将其设置为空数组。
另一种方法是将数组的长度设置为 0。
要清空数组,请将其 length
属性设置为 0。当数组的 length
属性更改时,索引不小于数组新长度的每个元素都会被自动删除。
const arr = ['a', 'b', 'c'];
arr.length = 0;
console.log(arr); // 👉️ []
通过将数组的 length
设置为0,我们自动从数组中删除所有索引不小于0的元素,从而覆盖整个数组。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
如何在 JavaScript 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。