Three methods for clearing arrays in JavaScript _ javascript tips

Source: Internet
Author: User
There are three methods for clearing arrays in JavaScript. For more information, see. Method 1, splice

The Code is as follows:


Var ary = [1, 2, 4];
Ary. splice (0, ary. length );
Console. log (ary); // output [], empty array, which is cleared


Method 2. The value of length is 0.
This method is very interesting. For other languages such as Java, the length of the array is read-only and cannot be assigned a value. For example

The Code is as follows:


Int [] ary = {1, 2, 4 };
Ary. length = 0;


An error will be reported in Java. In JS, yes, and the array is cleared,

The Code is as follows:


Var ary = [1, 2, 4];
Ary. length = 0;
Console. log (ary); // output [], empty array, which is cleared


Currently, clear of the Prototype array and empty of the array in the mootools library use this method to clear the array.
Method 3: assign a value to []

The Code is as follows:


Var ary = [1, 2, 4];
Ary = []; // assign a value to an empty array to clear the original array.


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

The above results show that method 3 is faster and more efficient. Therefore, if you do not retain other attributes of the original array, Ext is more recommended.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.