Summary of js array clearing (deletion) Method

Source: Internet
Author: User

There are many methods for clearing data in js. Below I will introduce several methods for clearing data, which can be used to compare with the performance of various array clearing methods. For more information, see.

Clearing the array is a common JavaScript job, but I often see it in an incorrect way. In many cases, developers will create a new array, such as the following:

Assign a value to []

The Code is as follows: Copy code

MyArray = []; // bad Method

Var ary = [1, 2, 4];
Ary = []; // assign a value to an empty array to clear the original array.

Creating an empty array to clear it is obviously not the best method. You should set the length attribute of the array to 0:

The Code is as follows: Copy code

MyArray. length = 0; // good!

Set length to zero to clear the current array, instead of creating another empty array! This helps you avoid array pointers. If you use the preceding method:


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

Set the length to 0 to clear both A and B.

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 );

The other attributes of the array are retained, and the method 3 is not retained. Many people think that method 2 is more efficient, because it only assigns a value to length, and method 3 creates an object again. It is tested that method 3 is highly efficient.

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: 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.