How to empty an array in JavaScript summary _javascript tips

Source: Internet
Author: User
Tags array length garbage collection

Way 1,splice

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

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

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

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 []

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:

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.

The above is a small set of JavaScript for you to empty the array of three ways, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.