Title: How to delete elements in an array in JS - with code examples
Text:
JavaScript is a powerful programming language that Provides rich array operation methods. In array operations, deleting elements is a common requirement. This article will introduce how to use JavaScript to delete elements in an array and provide specific code examples.
In JavaScript, we can use the following methods to delete elements in the array:
let fruits = ['apple', 'banana', 'orange', 'grape']; fruits.splice(1, 1); // 删除第二个元素 console.log(fruits); // 输出:['apple', 'orange', 'grape']
In the above code, we first create an array containing four fruits. We then removed the element with index 1 (i.e. 'banana') using the splice() method. Finally, we print the output and get the array after deleting the elements.
let vegetables = ['carrot', 'cabbage', 'broccoli', 'tomato']; delete vegetables[2]; // 删除第三个元素的值 console.log(vegetables); // 输出:['carrot', 'cabbage', empty, 'tomato']
In the above code, we first create an array containing four vegetables. We then deleted the element at index 2 (i.e. 'broccoli') using the delete keyword. It should be noted that the deleted array will leave an empty
value at the third position without reordering the index.
let numbers = [1, 2, 3, 4, 5]; let filteredNumbers = numbers.filter(function(value) { return value !== 3; // 过滤掉值为3的元素 }); console.log(filteredNumbers); // 输出:[1, 2, 4, 5]
In the above code, we first create an array containing five numbers. Then, we use the filter() method to filter out elements with a value of 3, and get a new array filteredNumbers. Finally, we print the output and get the array after deleting the elements.
To sum up, we have introduced three commonly used methods to delete elements in JavaScript arrays, including using the splice() method, delete keyword and filter() method. Select the appropriate method based on actual needs and combine it with specific code examples to easily delete elements in the array. I hope this article can be helpful to readers.
The above is the detailed content of How to delete elements in an array in js. For more information, please follow other related articles on the PHP Chinese website!