如何从数组中删除一个特定值? 类似 :

array.remove(value);

我必须使用核心核心核心JavaScript。 不允许框架 。


当前回答

此函数从特定位置的数组中删除元素。

array.remove(position);

Array.prototype.remove = function (pos) {
    this.splice(pos, 1);
}

var arr = ["a", "b", "c", "d", "e"];
arr.remove(2); // remove "c"
console.log(arr);

如果您不知道要删除的项目的位置, 请使用这个 :

array.erase(element);

Array.prototype.erase = function(el) {
    let p = this.indexOf(el); // indexOf use strict equality (===)
    if(p != -1) {
        this.splice(p, 1);
    }
}

var arr = ["a", "b", "c", "d", "e"];
arr.erase("c");
console.log(arr);

其他回答

不可改变和一班制方式:

const newArr = targetArr.filter(e => e !== elementToDelete);

定义:

function RemoveEmptyItems(arr) {
  var result = [];
  for (var i = 0; i < arr.length; i++) if (arr[i] != null && arr[i].length > 0) result.push(arr[i]);
  return result;
}

用法 :

var arr = [1,2,3, "", null, 444];
arr = RemoveEmptyItems(arr);
console.log(arr);
const arr = [1, 2, 3, 4, 5]
console.log(arr) // [ 1, 2, 3, 4, 5 ]

假设你想从Arr删除3号

const newArr = arr.filter(w => w !==3)
console.log(newArr) // [ 1, 2, 4, 5 ]

您永远不应该根据功能性编程模式改变您的阵列。 您可以创建一个新的阵列, 而不引用您想要更改的数据 ECMAScript 6 方法 。filter;

var myArray = [1, 2, 3, 4, 5, 6];

假设您想要删除5从数组中,您可以简单地这样做:

myArray = myArray.filter(value => value !== 5);

这将给您一个没有您想要删除的值的新数组。 因此结果将是 :

 [1, 2, 3, 4, 6]; // 5 has been removed from this array

关于进一步理解,请阅读MDN文件:Array.过滤器.

ES6且无突变:(2016年10月)

const removeByIndex = (list, index) =>
      [
        ...list.slice(0, index),
        ...list.slice(index + 1)
      ];
         
output = removeByIndex([33,22,11,44],1) //=> [33,11,44]
      
console.log(output)