Turn: JS empty array

Source: Internet
Author: User

Way 1,splice

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

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

0 S 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 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, assigned to []

1 2 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:

1 2 3 4 5 6 7 8 9 vara = []; for(vari=0; i< 1000000; i++){a.push(i);} var  start = &NBSP; new  date (); //a = [];  a.length = 0;  var  end = &NBSP; 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.

Turn from:

Http://www.2cto.com/kf/201409/335383.html

To delete an item or items in an array: http://www.cnblogs.com/Joans/p/3981122.html

Turn: JS empty array

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.