Summary of JS array emptying (delete) method

Source: Internet
Author: User

Emptying the array is a common JavaScript job, but I often see it in the wrong way. Many times, developers will create a new array, such as the following:

Assignment to []

The code is as follows Copy Code

MyArray = []; Bad way.

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

To create an empty array to empty it is obviously not the best way to set the length property of the array to 0:

The code is as follows Copy Code

myarray.length = 0; good!

Set length to zero empty the current array instead of creating another empty array! This can help you avoid pointer problems with arrays. If you use the previous method:

The code is as follows Copy Code
A = [1,2,3,4,5]
B = A
A = []
Console.log (B)//[1,2,3,4,5], the original array is still not empty, a just points to the new empty array


Set a length of 0 so that both A and B can be emptied.

The code is as follows Copy 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);

Other attributes of the array are preserved, 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.

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.