When it comes to JS arrays, we quickly think of various apis for arrays, including push/ POP/Shift for insert and delete, Map/Reduce /filter for higher-order transformations, There are other methods like sort, concat, slice, indexOf, and so on. But arrays do not have the clear method, which can be used to clear the entire array. This article describes several ways to clear an array.

Method 1

Directly empty, reinitialize

arr = [1.2.3]
arr = []
Copy the code

This way the performance is best because you declare a new array directly, which is equivalent to a variable initialization, without modifying the original array.

Method 2

Using the length property, remember that in JS, the length property of an array is not only readable, but also writable.

arr = [1.2.3]
arr.length = 0
Copy the code

This code sets the length of the array to 0, returns 0, and prints arR again on the console, printing []

Methods 3

Use the splice attribute

arr = [1.2.3]
arr.splice(0, arr.length)
Copy the code

The splice method takes two arguments. The first argument, 0, is the number of elements to be deleted. The second argument is the number of elements to be deleted. The splice method returns the deleted element, so this code returns [1, 2, 3], at which point arR is printed, printing the empty array []

Methods 4

Use the loop + POP/Shift method

Arr = [1, 2, 3] while (arr.length) {arr.pop() // similar, arr.shift()}Copy the code

Remove elements from the array by looping through the elements, using the array’s built-in Shift /pop methods, both of which modify the array directly. By comparing the previous methods, you can roughly guess that this method is the worst.

The benchmark

There are many websites that can run benchmarks for JS code to see how well different code is performing, using Jsben.

Here I randomly generate an array of several hundred elements for testing purposes.

Then paste the code of each of the above methods into the test pool, and the final result is as follows:

As you can see, method 1 is the fastest in this test because it initializes the new array directly; Method 2 (length = 0) is the second block, followed by method 3 (splice), and method 4 (pop/Shift) is the slowest.

conclusion

In everyday projects, if you need to empty an array, it is best to simply [] empty it.

Say so much, what is wrong or wrong, please correct!

(after)