Three ways to empty an array in JavaScript

Source: Internet
Author: User

Way 1,splice

1

2

3

var ary = [1,2,3,4];

Ary.splice (0,ary.length);

Console.log (ary); Output [], empty array, is emptied

Method 2,length is assigned a value of 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 error, compile pass. And JS can be, and the array is emptied,

1

2

3

var ary = [1,2,3,4];

ary.length = 0;

Console.log (ary); Output [], empty array, is emptied


The current prototype array in the clear and MooTools libraries in the empty array is used this way to empty the array.

Mode 3, assigned to []

1

2

var ary = [1,2,3,4];

ary = []; Assign to an empty array to clear the original array

In fact, this is not a strict meaning of the empty array, just the ARY is re-assigned to an empty array, before the array if there is no reference to it will wait for garbage collection.

The clear of the EXT library Ext.compositeelementlite class is cleared using this method.

Mode 2 retains the other properties of the array, and mode 3 is not preserved. Many people think that Mode 2 is more efficient because it simply re-assigns a value to length, and mode 3 re-establishes the object. The test is precisely the efficiency of mode 3. 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: 3 faster and more efficient. Therefore, if you do not preserve the other properties of the original array, the method of ext is more recommendable.

Three ways to empty an array in JavaScript

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.