1.使用splice()方法刪除元素
JavaScript 中的 splice() 方法可用于在數(shù)組中添加或刪除元素。如果我們需要刪除數(shù)組中的元素,可以使用 splice() 方法。該方法接受兩個參數(shù),第一個參數(shù)指定要刪除的元素的位置,第二個參數(shù)指定要刪除的元素個數(shù):
let myArray = ["apple", "banana", "orange", "grape"];
myArray.splice(1, 1);
console.log(myArray); // ["apple", "orange", "grape"]
2.使用filter()方法刪除元素
除了使用 splice() 方法,我們還可以使用 filter() 方法來刪除數(shù)組中的元素。該方法可用于創(chuàng)建一個新的數(shù)組,其中包含符合特定條件的元素。我們可以使用以下代碼刪除數(shù)組中的所有 “banana” 元素:
let myArray = ["apple", "banana", "orange", "grape"];
myArray = myArray.filter(function(item) {
return item !== "banana"
});
console.log(myArray); // ["apple", "orange", "grape"]
3.使用pop()和shift()方法刪除元素
pop() 和 shift() 方法可用于刪除數(shù)組的最后一個元素和第一個元素。如果我們想刪除數(shù)組中的特定元素,可以使用這些方法與?indexOf() 方法結(jié)合使用。例如,以下代碼可以刪除數(shù)組中的第二個元素:
let myArray = ["apple", "banana", "orange", "grape"];
let index = myArray.indexOf("banana");
if (index !== -1) {
myArray.splice(index, 1);
}
console.log(myArray); // ["apple", "orange", "grape"]
4.使用slice()方法刪除元素
slice() 方法是一個純函數(shù),它不會改變原始數(shù)組,而是返回一個新的數(shù)組,該數(shù)組包含從開始到結(jié)束(不包含結(jié)束)的元素。我們可以使用以下代碼刪除數(shù)組中的第二個元素:文章來源:http://www.zghlxwxcb.cn/news/detail-761720.html
let myArray = ["apple", "banana", "orange", "grape"];
let newArray = myArray.slice(0, 1).concat(myArray.slice(2));
console.log(newArray); //["apple", "orange", "grape"]
5.使用ES6的filter()方法刪除元素
ES6 中的 filter() 方法也可以用于刪除數(shù)組中的元素。我們可以使用以下代碼刪除數(shù)組中的所有 “banana” 元素:文章來源地址http://www.zghlxwxcb.cn/news/detail-761720.html
let myArray = ["apple", "banana", "orange", "grape"];
myArray = myArray.filter(item => item !== "banana");
console.log(myArray); // ["apple", "orange", "grape"]
到了這里,關(guān)于js 刪除數(shù)組中指定元素——5種方式的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!