Home  >  Article  >  Web Front-end  >  Three ways to clear arrays in JavaScript_javascript skills

Three ways to clear arrays in JavaScript_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:08:191370browse

Method 1, splice

Copy code The code is as follows:

var ary = [1,2, 3,4];
ary.splice(0,ary.length);
console.log(ary); // Output [], empty array, that is, cleared

Method 2, assign length to 0
This method is very interesting. In other languages ​​such as Java, the length of the array is read-only and cannot be assigned. For example,
Copy code The code is as follows:

int[] ary = {1,2,3 ,4};
ary.length = 0;

An error will be reported in Java and the compilation will not pass. In JS, it is possible, and the array is cleared,
Copy the code The code is as follows:

var ary = [1,2,3,4];
ary.length = 0;
console.log(ary); // Output [], empty array, that is, cleared

Currently, clear for arrays in Prototype and empty for arrays in the mootools library use this method to clear arrays.
Method 3, assignment is []
Copy code The code is as follows:

var ary = [1,2,3,4];
ary = []; // Assign an empty array to clear the original array

Method 2 retains other attributes of the array, method 3 is not retained. Many people think that method 2 is more efficient because it only reassigns length, while method 3 re-creates an object. After testing, it is precisely method 3 that is most efficient. Test code:
Copy code The code is as follows:

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);

Test results:

Three ways to clear arrays in JavaScript_javascript skills

As you can see from the above results: Method 3 is faster and more efficient. Therefore, if the other attributes of the original array are not retained, the method used by Ext is more recommended.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn