Array.prototype.indexOf()
用indexOf找到你想刪除的數組元素的索引,然後用splice刪除該索引。
const array = [2, 5, 9];
console.log(array);
const index = array.indexOf(5);
if (index > -1) {
array.splice(index, 1);
}
// array = [2, 9]
console.log(array); splice的第二個參數是要移除的元素的數量。注意,splice修改了原地的數組,並返回一個包含被移除的元素的新數組。
為了完整起見,這裡有一些函數。第一個函數只刪除單一的出現(即從[2,5,9,1,5,8,5]中刪除5的第一個匹配),而第二個函數則刪除所有出現的情況。
function removeItemOnce(arr, value) {
var index = arr.indexOf(value);
if (index > -1) {
arr.splice(index, 1);
}
return arr;
}
function removeItemAll(arr, value) {
var i = 0;
while (i < arr.length) {
if (arr[i] === value) {
arr.splice(i, 1);
} else {
++i;
}
}
return arr;
}
// Usage
console.log(removeItemOnce([2,5,9,1,5,8,5], 5))
console.log(removeItemAll([2,5,9,1,5,8,5], 5))在TypeScript中,這些函數可以添加類型參數。
function removeItem<T>(arr: Array<T>, value: T): Array<T> {
const index = arr.indexOf(value);
if (index > -1) {
arr.splice(index, 1);
}
return arr;
}Array.prototype.filter()
var value = 3
var arr = [1, 2, 3, 4, 5, 3]
arr = arr.filter(function(item) {
return item !== value
})
console.log(arr)
// [ 1, 2, 4, 5 ]原創文章,作者:投稿專員,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/256145.html
微信掃一掃
支付寶掃一掃