Home >Web Front-end >JS Tutorial >How to Efficiently Empty an Array in JavaScript?
How to Clear an Array in JavaScript
Question: How can I efficiently empty an array in JavaScript?
Answer: There are several methods to clear an array in JavaScript:
This approach sets the length property of the array to 0.
const A = [1, 2, 3, 4]; A.length = 0; console.log(A); // []
The splice method can be used with parameters that specify a starting index of 0 and a deletion count equal to the array's length.
const A = [1, 2, 3, 4]; A.splice(0, A.length); console.log(A); // []
Iteratively popping elements from the array using a while loop is another option. However, this method is typically slower.
const A = [1, 2, 3, 4]; while (A.length > 0) { A.pop(); } console.log(A); // []
This approach creates a new empty array and assigns it to the existing array variable.
const A = [1, 2, 3, 4]; A = []; console.log(A); // []
Performance Considerations:
Among these methods, setting the array length to 0 and using the splice method are the most efficient in terms of execution speed.
The above is the detailed content of How to Efficiently Empty an Array in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!