How to clear javascript arrays _ javascript tips

Source: Internet
Author: User
This is a very basic problem, but we often do something wrong. Here we will share it with you to make it easier for a friend who needs to clear an array. Many people use the following method:

The Code is as follows:


A = [];



We know that javascript variable storage methods can be divided into reference types and direct quantities. The array belongs to the object, that is, the reference type. It references the variable pointer address, which is designed to save memory.

In addition, if the preceding empty array method is used to assign a new array directly, the previously referenced array may not be released (with other references ), for example, the following code:

The Code is as follows:


Var a = [2, 3];
Var B =;
A = [];
Console. log (B );



At this time, a and B are not the same array. After a is cleared, B still refers to the referenced address. unless you mean it, this will pose a risk.

Therefore, the best way to empty the array is to set the length to 0, that is:

The Code is as follows:


A. length = 0;



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.