Home >Web Front-end >JS Tutorial >Share three ways to clear arrays in JavaScript (with code)

Share three ways to clear arrays in JavaScript (with code)

yulia
yuliaOriginal
2018-09-17 15:22:301469browse

JavaScript is widely used in front-end development. Today I will share with you three ways to clear arrays in JavaScript, as well as a comparison between the three methods. You can refer to it if you need it.

Method 1, splice

var ary = [1,2,3,4];
ary.splice(0,ary.length);
console.log(ary); // 输出 [],空数组,即被清空了

Method 2, assign length to 0

This method is very interesting, other languages For example, in Java, the length of its array is read-only and cannot be assigned. For example,

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

will report an error in Java and fail to compile. In JS, it is possible, and the array is cleared.

var ary = [1,2,3,4];
ary.length = 0;
console.log(ary); // 输出 [],空数组,即被清空了

Currently, the clear of the array in Prototype and the empty of the array in the mootools library use this method to clear the array.

Method 3. Assign the value to []

var ary = [1,2,3,4];
ary = []; // 赋值为一个空数组以达到清空原数组

This is not actually a clearing of the array in the strict sense. It just reassigns ary to an empty array. The previous array If there are no references pointing to it it will wait for garbage collection.

Ext library Ext.CompositeElementLite class clear uses this method to clear.

Method 2 retains other attributes of the array, while method 3 does not. 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:

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 result:

Share three ways to clear arrays in JavaScript (with code)

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.

The above is the detailed content of Share three ways to clear arrays in JavaScript (with code). For more information, please follow other related articles on the PHP Chinese website!

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