Home > Web Front-end > JS Tutorial > What are the methods to clear arrays in javascript

What are the methods to clear arrays in javascript

coldplay.xixi
Release: 2023-01-03 09:32:07
Original
2619 people have browsed it

Javascript method to clear an array: 1. Use the splice method, the code is [ary.splice(0,ary.length)]; 2. Assign length to 0, the code is [ary.length = 0;] .

What are the methods to clear arrays in javascript

The operating environment of this tutorial: Windows 7 system, JavaScript version 1.8.5, DELL G3 computer.

Javascript method to clear array:

Method 1, splice

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

Method 2, length assignment is 0

This method is very interesting. In other languages ​​such as Java, the length of the array is read-only and cannot be assigned. For example,

int[] ary = {1,2,3,4}; 
ary.length = 0;
Copy after login

will report an error in Java and fail to compile.

In JS, it is possible, and the array is cleared. For example,

var ary = [1,2,3,4]; 
ary.length = 0; 
console.log(ary); // 输出 [],空数组,即被清空了
Copy after login

Currently, the clear method of the array in Prototype and the empty method of the array in the mootools library use this method to clear the array.

Method 3, assign value to []

var ary = [1,2,3,4]; 
ary = []; // 赋值为一个空数组以达到清空原数组
Copy after login

The clear method of the Ext.CompositeElementLite class in the Ext library uses this method to clear.

Related free learning recommendations: javascript video tutorial

The above is the detailed content of What are the methods to clear arrays in javascript. For more information, please follow other related articles on the PHP Chinese website!

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