How to delete an element from a js array requires specific code examples
In JavaScript, if we need to delete an element from an array, there are several ways to do it accomplish. These methods are described in detail below and corresponding code examples are provided.
The following is a code example of using the splice() method to delete an element:
var fruits = ["apple", "banana", "orange"]; fruits.splice(1, 1); // 删除索引为1的元素,即删除"banana" console.log(fruits); // 输出:["apple", "orange"]
The following is a code example of using the filter() method to delete an element:
var fruits = ["apple", "banana", "orange"]; fruits = fruits.filter(function(value) { return value !== "banana"; // 返回不等于"banana"的元素 }); console.log(fruits); // 输出:["apple", "orange"]
The following is a code example of using the delete keyword to delete an element:
var fruits = ["apple", "banana", "orange"]; delete fruits[1]; // 删除索引为1的元素,即删除"banana" console.log(fruits); // 输出:["apple", undefined, "orange"]
It should be noted that although the delete keyword can be used to delete elements, we do not recommend it. This method removes an element from an array because it leaves a hole (undefined).
The above are several common methods to delete an element in an array in JavaScript. You can choose the appropriate method to delete elements in the array according to your needs.
The above is the detailed content of How to delete an element from js array. For more information, please follow other related articles on the PHP Chinese website!