Home > Web Front-end > JS Tutorial > body text

Detailed introduction to three ways to clear arrays in JavaScript

黄舟
Release: 2017-03-22 14:24:36
Original
1690 people have browsed it

This article mainly introduces three ways to clear arrays in JavaScript. Has very good reference value. Let’s take a look at it with the editor

Method 1, splice

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

Method 2, length assignment is 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,

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

will report an error in Java and fail to compile.

In JS, it is possible, and the array is cleared. For example,

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

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

Method 3, assign value to []

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

The clear method of the Ext.CompositeElementLite class in the Ext library 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);
Copy after login

Test result:

##a.length= 09429141431 a=[]0000 000
IE6 IE7 IE8 IE9 Firefox Safari Chrome
The above results can be seen: method 3 is faster and more efficient.

Judging from the test results, the method used by Ext is more recommended if other attributes of the original array are not retained.

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!