Three ways to empty an array in JavaScript

Source: Internet
Author: User
Tags array length

Mode 1, Splice
123 varary = [1,2,3,4];ary.splice(0,ary.length);console.log(ary); // 输出 [],空数组,即被清空了

Detailed Description: http://www.w3school.com.cn/jsref/jsref_splice.asp

Method 2, length is assigned to 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

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

Java will error, compile pass. And JS can be, and the array is emptied,

123 varary = [1,2,3,4];ary.length = 0;console.log(ary); // 输出 [],空数组,即被清空了


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

Mode 3, assignment = []
12 varary = [1,2,3,4];ary = []; // 赋值为一个空数组以达到清空原数组

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:

123456789 vara = [];for(vari=0; i< 1000000; i++){    a.push(i);}var start = newDate();//a = [];a.length = 0;varend = newDate();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.

Original: http://www.cnblogs.com/snandy/archive/2011/04/04/2005156.html

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.