本篇内容主要讲解“JS删除数组中某个元素的方式有哪些”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“JS删除数组中某个元素的方式有哪些”吧!
var arr = [1,2,3,4,5] var new_arr = arr.slice(0, -1) // arr => [1,2,3,4,5] // new_arr => [1,2,3,4] var arr = [1,2,3,4,5] var new_arr = arr.slice(0, arr.length - 1) // arr => [1,2,3,4,5] // new_arr => [1,2,3,4]
var arr = [1,2,3,4,5] var new_arr = arr.splice(-1) // arr => [1,2,3,4] // new_arr => [5] var arr = [1,2,3,4,5] var new_arr = arr.splice(-1, 1) // arr => [1,2,3,4] // new_arr => [5] var arr = [1,2,3,4,5] var new_arr = arr.splice(arr.length - 1) // arr => [1,2,3,4] // new_arr => [5] var arr = [1,2,3,4,5] var new_arr = arr.splice(arr.length - 1, 1) // arr => [1,2,3,4] // new_arr => [5]
var arr = [1,2,3,4,5] arr.pop() // arr => [1,2,3,4]
var arr = [1,2,3,4,5] var new_arr = [] for (let i = 0, len = arr.length; i < len; i++) { if (i < len - 1) { new_arr.push(arr[i]) } } // arr => [1,2,3,4,5] // new_arr => [1,2,3,4]
var arr = [1,2,3,4,5] arr.length = arr.length - 1 // arr => [1,2,3,4]
var arr = [1,2,3,4,5] var new_arr = arr.slice(1) // arr => [1,2,3,4,5] // new_arr => [2,3,4,5]
var arr = [1,2,3,4,5] var new_arr = arr.splice(0, 1) // arr => [2,3,4,5] // new_arr => [1]
var arr = [1,2,3,4,5] arr.shift() // arr => [2,3,4,5]
var arr = [1,2,3,4,5], element = 2 arr = arr.filter(item => item != element) // arr => [1,3,4,5]
var element = 2, arr = [1,2,3,4,5] arr.splice(arr.indexOf(2), 1) // arr => [1,3,4,5]
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]
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]
var delete_index = 2 var arr = [1,2,3,4,5] // arr => [1,2,3,4,5] var new_arr = arr.splice(delete_index, 1) // new_arr => [3] // arr => [1,2,4,5]
var delete_index = 2, arr = [1,2,3,4,5], new_arr = [] for (let i = 0, len = arr.length; i < len; i++) { if (i != delete_index) { new_arr.push(arr[i]) } } // arr => [1,2,3,4,5] // new_arr => [1,2,4,5]
注意:
1. 不可以使用 delete 方式删除数组中某个元素,此操作会造成稀疏数组,被删除的元素的位置依然存在,为 empty,且数组的长度不变。
2. 不可以使用 forEach 方法比对数组的下标值,因为 forEach 在循环的时候是无序的。
到此,相信大家对“JS删除数组中某个元素的方式有哪些”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。