Home > Web Front-end > JS Tutorial > body text

How to delete all elements from a javascript array

青灯夜游
Release: 2023-01-04 09:34:55
Original
6737 people have browsed it

Method: 1. Use the "arr=[]" statement to delete; 2. Use the "arr.length=0" statement to delete; 3. Use the splice() function, the syntax "arr.splice(0 , arr.length)"; 4. Use a while loop with pop() or shift() to delete.

How to delete all elements from a javascript array

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

JavaScript method to delete all elements in the Array array

var arr = [1,2,3,4];
Copy after login

Method 1: Direct assignment

arr = [];
Copy after login

How to delete all elements from a javascript array

Assign the empty array directly to the variable arr. The new array has no reference relationship with the original one. Operations on the new array will not affect the original array.

Method 2: Set length

arr.length = 0
Copy after login

How to delete all elements from a javascript array

Directly set the array length to 0. This method is not available in all JS engines. It will work in "strict mode", and this method will not work because arr.length is read-only.

Method 3: splice

arr.splice(0, arr.length)
Copy after login

How to delete all elements from a javascript array

This method will return all the deleted elements and form a new array, but There is no performance impact and a reference to the array will be maintained.

[Recommended learning: javascript advanced tutorial]

Method 4: pop()

while(arr.length > 0) {
    arr.pop();
}
Copy after login

How to delete all elements from a javascript array

Performance is poor.

Method 5: shift()

while (arr.length > 0) {
  arr.shift();
}
Copy after login

How to delete all elements from a javascript array

This is the method with the worst performance.

For more programming related knowledge, please visit: Programming Video! !

The above is the detailed content of How to delete all elements from a javascript array. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!