js删除数组中某个指定元素
作者:xlnxin发布时间:2023-10-06分类:其他教程浏览:486
导读:filter删除12345vararr=[1,2,3,4,5], element=2 arr=a...
filter 删除
1 2 3 4 5 | var arr = [1,2,3,4,5], element = 2 arr = arr.filter(item => item != element) // arr => [1,3,4,5] |
splice 删除
1 2 3 4 5 | var element = 2, arr = [1,2,3,4,5] arr.splice(arr.indexOf(2), 1) // arr => [1,3,4,5] |
forEach、map、for 删除
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | var arr = [1,2,3,4,5], element = 2, new_arr = [] arr.forEach(item => (item != element && new_arr.push(item))) // new_arr => [1,3,4,5] // map 同理 var arr = [1,2,3,4,5], element = 2, new_arr = [] for (let i = 0; i < arr.length; i++) { arr[i] != element && new_arr.push(arr[i]) } // new_arr => [1,3,4,5] |
set 删除
1 2 3 4 5 6 | var arr = [1,2,3,4,5], element = 2 var new_set = new Set(arr) new_set. delete (element) var new_arr = [...new_set] // new_arr => [1,3,4,5] |
标签:js
- 上一篇:js删除数组第一个元素
- 下一篇:JS二维数组对象根据指定key进行排序
- 其他教程排行
- 最近发表