Arrays are a very common and important data type in JavaScript, and deleting array elements is a common array operation. JavaScript has many built-in functions for deleting array elements, so deleting array elements is not a problem for us. Not difficult. So how to implement the advanced version of deleting array elements - clearing the array? Today we will learn how to clear all elements of a JS array.
In this article, we will introduce to you 4 methods of clearing arrays in JS, and use code examples to see how to clear the array (delete all elements of the array).
[Recommended learning:javascript advanced tutorial]
Method 1: Directly assign an empty array[]
var arr=new Array("香蕉","苹果","梨子","橙子","橘子","榴莲"); console.log(arr); arr=[]; console.log(arr);
Output result:
This method does not strictly clear the array, but just reassigns arr to an empty array.
Method 2: Use the length attribute to set the array length to 0
The length attribute can set or return the array length. When the value of the length attribute is less than the length of the array itself, subsequent elements in the array will be truncated; if the value of the length attribute is 0, the entire array can be cleared.
var arr=new Array("香蕉","苹果","梨子","橙子","橘子","榴莲"); console.log(arr); arr.length=0; console.log(arr);
Output result:
When the value of the length attribute is greater than its own length, the array length will be extended, and the remaining elements will be undefined.
Method 3: Use splice() to delete all array elements
Use the splice() method to delete one or more array elements after the specified subscript position. You only need to specify the splice() method to start from the first array element, and the number of elements to be deleted isarr.length
to clear the array.
var arr=new Array("香蕉","苹果","梨子","橙子","橘子","榴莲"); console.log(arr); arr.splice(0,arr.length); console.log(arr);
Output result:
Method 4: Use delete operator
delete operator can be used Delete the array element with the specified subscript. The deleted elements are empty elements and the length of the deleted array remains unchanged.
Use delete operator and loop statement to clear the array
var arr=new Array("香蕉","苹果","梨子","橙子","橘子","榴莲"); console.log(arr); for(var i=0;i<=arr.length;i++){ delete arr[i]; } console.log(arr);
Output result:
For more programming related knowledge, please visit :Introduction to Programming! !
The above is the detailed content of JS array learning: 4 ways to clear all elements (detailed code explanation). For more information, please follow other related articles on the PHP Chinese website!