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

array.remove(value);

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


当前回答

我对基底 JavaScript 阵列进行了相当高效的扩展:

Array.prototype.drop = function(k) {
  var valueIndex = this.indexOf(k);
  while(valueIndex > -1) {
    this.removeAt(valueIndex);
    valueIndex = this.indexOf(k);
  }
};

其他回答

很简单,只要做:

var arr = [1,2,4,5];
arr.splice(arr.indexOf(5), 1);
console.log(arr); // [1,2,4];

更现代一点ECMAScript 2015(原称和谐或ES6)方法。

const items = [1, 2, 3, 4];
const index = 2;

然后:

items.filter((x, i) => i !== index);

弹出 :

[1, 2, 4]

您可以使用贝贝以及 a 和 a多元填充服务以确保在浏览器之间得到很好的支持。

以下是几个方法使用 JavaScript 从数组中删除项目.

描述的所有方法不变换原始数组,而不是创造一个新的。

如果您知道某个项目的索引

假设您有一个数组,而您想要删除位置中的项目i.

一种方法是使用slice():

const items = ['a', 'b', 'c', 'd', 'e', 'f']
const i = 3
const filteredItems = items.slice(0, i).concat(items.slice(i+1, items.length))

console.log(filteredItems)

slice()创建新数组, 使用它收到的索引 。 我们简单地创建一个新数组, 从开始到要删除的索引, 并且将另一个数组从我们删除的后第一个位置集中到数组的末尾 。

如果您知道数值

在这种情况下,一个好的选择是使用filter(),它提供了更多宣示方针:

const items = ['a', 'b', 'c', 'd', 'e', 'f']
const valueToRemove = 'c'
const filteredItems = items.filter(item => item !== valueToRemove)

console.log(filteredItems)

此选项使用 ES6 箭头函数。 您可以使用传统函数支持旧的浏览器 :

const items = ['a', 'b', 'c', 'd', 'e', 'f']
const valueToRemove = 'c'
const filteredItems = items.filter(function(item) {
  return item !== valueToRemove
})

console.log(filteredItems)

或者你可以使用 Babel 将ES6代码转换回ES5, 使旧浏览器更容易消化, 而在您的代码中写入现代 JavaScript 。

删除多个项目

如果不是单项,而是要删除许多项,会怎么样?

让我们找到最简单的解决方案

按指数分列的指数

您可以在序列中创建函数并删除项目 :

const items = ['a', 'b', 'c', 'd', 'e', 'f']

const removeItem = (items, i) =>
  items.slice(0, i-1).concat(items.slice(i, items.length))

let filteredItems = removeItem(items, 3)
filteredItems = removeItem(filteredItems, 5)
//["a", "b", "c", "d"]

console.log(filteredItems)

以数值计

您可以在回溯函数中搜索包含内容 :

const items = ['a', 'b', 'c', 'd', 'e', 'f']
const valuesToRemove = ['c', 'd']
const filteredItems = items.filter(item => !valuesToRemove.includes(item))
// ["a", "b", "e", "f"]

console.log(filteredItems)

避免突变原始数组

splice()(不与slice()变换原始数组,并应避免。

(最初张贴在我的网站上)https://flaviocopes.com/how-to-remove-item-from-array/)

Array.prototype.removeItem = function(a) {
    for (i = 0; i < this.length; i++) {
        if (this[i] == a) {
            for (i2 = i; i2 < this.length - 1; i2++) {
                this[i2] = this[i2 + 1];
            }
            this.length = this.length - 1
            return;
        }
    }
}

var recentMovies = ['Iron Man', 'Batman', 'Superman', 'Spiderman'];
recentMovies.removeItem('Superman');

删除上次的元素

arrName.pop();

删除第一个元素

arrName.shift();

从中间删除

arrName.splice(starting index, number of element you wnt to delete);

Example: arrName.splice(1, 1);

删除最后一个元素

arrName.splice(-1);

使用数组索引编号删除

 delete arrName[1];