本文介绍如何删除 JavaScript 数组中的元素。
以下实例我们自定义一个删除数组元素的方法:
- Array.prototype.removeByValue = function (val) {
- for (var i = 0; i < this.length; i++) {
- if (this[i] === val) {
- this.splice(i, 1);
- i--;
- }
- }
- return this;
- }
-
- var sites = ['apple', 'google', 'cdsy', 'taobao'];
- sites.removeByValue('google');
-
- console.log(sites);
- // -> ['apple', 'cdsy', 'taobao']
也可以使用array.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);
以下实例设置了可以删除一个或多个数组中的元素:
- 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))