Home > Web Front-end > JS Tutorial > How to clear javascript array_javascript tips

How to clear javascript array_javascript tips

WBOY
Release: 2016-05-16 17:34:04
Original
1121 people have browsed it

When an array needs to be cleared, many people use the following method:

Copy code The code is as follows:

a = [];


We know that JavaScript variable storage methods are divided into reference types and direct quantities. Arrays belong to objects, that is, reference types, and they refer to variable pointer addresses. The reason why they are designed this way is to save memory.

As for the above method of emptying an array, if you directly assign a new array, the previously referenced array may not be released (there are other references), such as the following code:

Copy code The code is as follows:

var a = [2,3];
var b = a;
a = [];
console.log(b);


At this time a and b are not the same array and are cleared. a and b still point to the previous reference address. Unless you do it intentionally, there will be hidden dangers.

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

Copy code The code is as follows:

a.length = 0;


Reprinted from JS8.IN ™
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template