Emptying the array is a common JavaScript job, but I often see it in the wrong way. Many times, developers will create a new array, such as the following:
Assignment to []
The code is as follows |
Copy Code |
MyArray = []; Bad way. var ary = [1,2,3,4]; ary = []; Assignment to an empty array to empty the original array |
To create an empty array to empty it is obviously not the best way to set the length property of the array to 0:
The code is as follows |
Copy Code |
myarray.length = 0; good! |
Set length to zero empty the current array instead of creating another empty array! This can help you avoid pointer problems with arrays. If you use the previous method:
The code is as follows |
Copy Code |
A = [1,2,3,4,5] B = A A = [] Console.log (B)//[1,2,3,4,5], the original array is still not empty, a just points to the new empty array |
Set a length of 0 so that both A and B can be emptied.
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); |
Other attributes of the array are preserved, and mode 3 is not retained. A lot of people think that Mode 2 is more efficient because it only assigns length to the value, and mode 3 builds the object again. The test is precisely the way 3 efficiency is high.