This article mainly introduces two methods for clearing the array elements in JavaScript, lists several common methods for clearing the array elements in javascript, and compares the two common methods, it has some reference value. If you need it, you can refer to the examples in this article to describe two simple methods for clearing array elements in JavaScript. Share it with you for your reference. The specific analysis is as follows:
There are multiple methods to clear arrays in JavaScript:
Var arr = [1, 2, 3]; arr = []; // method 1 arr. length = 0; // method 2 arr = null; // method 3 delete arr; // Method 4
The first and second most commonly used
Var arr = [1, 2, 3]; // method 1 // advantage: This method is safer if elements in the array arr are used elsewhere. It is also simple and fast // disadvantage: it increases the extra memory overhead and reopens a new empty array arr = []; // method 2 // advantages: if you want to synchronize the effect of the cleared arr element to other places where the arr element is used, it is better to use this option. // disadvantage: After setting the length attribute of the array, this will cause the array to delete the elements whose index is the length and later, so the performance overhead is very high // This method is also the worst of the four methods. Arr. length = 0;
I hope this article will help you design javascript programs.