Three ways to empty an array in JavaScript __java

Source: Internet
Author: User
Tags array length

Way 1,splice

1 2 3 var ary = [1,2,3,4]; Ary.splice (0,ary.length); Console.log (ary); The output [], an empty array, is emptied

method 2,length assignment to 0

This is interesting, and other languages such as Java, whose array length is read-only, cannot be assigned a value. Such as

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

Java will be an error, compile pass. And JS can, and empty the array,

1 2 3 var ary = [1,2,3,4]; ary.length = 0; Console.log (ary); The output [], an empty array, is emptied

The current prototype the array's clear and the empty of the array in the MooTools library use this way to empty the array.

mode 3, assigned to []

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

This is not really a strictly clear empty array, just ary the value to an empty array, and the previous array will wait for garbage collection if no reference is directed at it.

The EXT Library Ext.compositeelementlite class's clear is emptied using this method.

Mode 2 preserves the other attributes of the array, and mode 3 is not retained. A lot of people think that Mode 2 is more efficient because it only assigns length to the value, and mode 3 builds the object again. The test is precisely the way 3 efficiency is high. Test code:

1 2 3 4 5 6 7 8 9 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 can be seen: Mode 3 faster, more efficient. So if you don't keep the other attributes of the original array, the way you use it 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.