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.
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 = [];
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
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)
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(); }
Performance is poor.
Method 5: shift()
while (arr.length > 0) { arr.shift(); }
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!