Home >Web Front-end >JS Tutorial >How to delete all elements from a javascript array

How to delete all elements from a javascript array

青灯夜游
青灯夜游Original
2021-04-07 18:29:466804browse

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

Method 1: Direct assignment

arr = [];

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

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)

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

How to delete all elements from a javascript array

Performance is poor.

Method 5: shift()

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

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!

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