Three methods for clearing arrays in JavaScript

Source: Internet
Author: User

Three methods for clearing arrays in JavaScript

Method 1, splice

123 var ary = [1,2,3,4];ary.splice(0,ary.length);console.log(ary);// OutputArray [0], empty Array, 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

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

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

123 var ary = [1,2,3,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 []

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

In fact, it cannot be said that the array is strictly cleared, but the array is re-assigned to an empty array. If the previous array is not referenced and pointed to it, it will wait for garbage collection.

Clear the Ext. CompositeElementLite class using this method.

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:

123456789 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.