30秒学会 JavaScript 片段 · 2023年10月22日

30秒学会 JavaScript 片段 – How do I empty an array in JavaScript?

When working with JavaScript arrays, a pretty common question is how does one empty an array and remove all its elements. As it turns out, there are a few ways you can go about this, each one with its pros and cons.

Assign it to an empty array

You can assign your variable to an empty array ([]) in order to clear it. While this option is rather fast, you should be mindful of references to the original array, as they will remain unchanged. Moreover, it doesn’t work for arrays declared as const.

代码实现

let a = [1, 2, 3, 4];
a = [];

Set its length to 0

A better option is to set the length of the array to 0. This option is also pretty fast and has the additional benefit of working for const variables.

使用样例

let a = [1, 2, 3, 4];
a.length = 0;

Use Array.prototype.splice()

Array.prototype.splice() can also be a useful alternative when trying to empty an array. While it has no other downsides compared to the previous method, it doesn’t seem to perform as well, so that might be something to consider.

let a = [1, 2, 3, 4];
a.splice(0, a.length);

Use Array.prototype.pop()

Last but not least, using Array.prototype.pop() is another, more old-fashioned option. It’s generally more verbose and less performant, so I’d rather use one of the previous methods instead.

let a = [1, 2, 3, 4];
while (a.length) a.pop();

翻译自:https://www.30secondsofcode.org/js/s/empty-array