There are many methods for clearing data in js. Below I will introduce several methods for clearing data, which can be used to compare with the performance of various array clearing methods. For more information, see.
Clearing the array is a common JavaScript job, but I often see it in an incorrect way. In many cases, developers will create a new array, such as the following:
Assign a value to []
The Code is as follows: |
Copy code |
MyArray = []; // bad Method Var ary = [1, 2, 4]; Ary = []; // assign a value to an empty array to clear the original array. |
Creating an empty array to clear it is obviously not the best method. You should set the length attribute of the array to 0:
The Code is as follows: |
Copy code |
MyArray. length = 0; // good! |
Set length to zero to clear the current array, instead of creating another empty array! This helps you avoid array pointers. If you use the preceding method:
The Code is as follows: |
Copy code |
A = [1, 2, 3, 4, 5] B = A = [] Console. log (B) // [1, 2, 3, 4, 5]. The original array is still not cleared. A just points to the new empty array. |
Set the length to 0 to clear both A and B.
The Code is as follows: |
Copy code |
Var a = []; For (var I = 0; I <1000000; I ++ ){ A. push (I ); } Var start = new Date (); // A = []; A. length = 0; Var end = new Date (); Alert (end-start ); |
The other attributes of the array are retained, and the method 3 is not retained. Many people think that method 2 is more efficient, because it only assigns a value to length, and method 3 creates an object again. It is tested that method 3 is highly efficient.