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

array.remove(value);

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


当前回答

强调.js可用于解决多个浏览器的问题。 如果存在的话, 它会使用在建浏览器的方法。 如果像旧版的互联网探索者一样缺少这些方法, 它会使用自己的自定义方法 。

从数组中删除元素( 从网站) 的简单示例 :

_.without([1, 2, 1, 0, 3, 1, 4], 0, 1); // => [2, 3, 4]

其他回答

以下是几个方法使用 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/)

Vanilla JavaScript(ES5.1) - (ES5.1) -已经到位版本版本

浏览器支持 :因特网探索者 9或以后(或以后(详细浏览器支持)

/**
 * Removes all occurences of the item from the array.
 *
 * Modifies the array “in place”, i.e. the array passed as an argument
 * is modified as opposed to creating a new array. Also returns the modified
 * array for your convenience.
 */
function removeInPlace(array, item) {
    var foundIndex, fromIndex;

    // Look for the item (the item can have multiple indices)
    fromIndex = array.length - 1;
    foundIndex = array.lastIndexOf(item, fromIndex);

    while (foundIndex !== -1) {
        // Remove the item (in place)
        array.splice(foundIndex, 1);

        // Bookkeeping
        fromIndex = foundIndex - 1;
        foundIndex = array.lastIndexOf(item, fromIndex);
    }

    // Return the modified array
    return array;
}

Vanilla JavaScript(ES5.1) - (ES5.1) -不可变版本版本

浏览器支持: 与原版的香草 JavaScript 相同

/**
 * Removes all occurences of the item from the array.
 *
 * Returns a new array with all the items of the original array except
 * the specified item.
 */
function remove(array, item) {
    var arrayCopy;

    arrayCopy = array.slice();

    return removeInPlace(arrayCopy, item);
}

香草ES6 -不可变版本版本

浏览器支持: Chrome 46, 边缘 12, Firefox 16, Opera 37, Safari 8 ()详细浏览器支持)

/**
 * Removes all occurences of the item from the array.
 *
 * Returns a new array with all the items of the original array except
 * the specified item.
 */
function remove(array, item) {
    // Copy the array
    array = [...array];

    // Look for the item (the item can have multiple indices)
    let fromIndex = array.length - 1;
    let foundIndex = array.lastIndexOf(item, fromIndex);

    while (foundIndex !== -1) {
        // Remove the item by generating a new array without it
        array = [
            ...array.slice(0, foundIndex),
            ...array.slice(foundIndex + 1),
        ];

        // Bookkeeping
        fromIndex = foundIndex - 1;
        foundIndex = array.lastIndexOf(item, fromIndex)
    }

    // Return the new array
    return array;
}

使用欧 6扩展操作员 。

比方说你想删除4。

let array = [1,2,3,4,5]
const index = array.indexOf(4)
let new_array = [...array.slice(0,index), ...array.slice(index+1, array.length)]
console.log(new_array)
=> [1, 2, 3, 5]

OK,OK, OK, OK, OK, OK, OK, OK, OK,OK, OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,例如,您有下面的数组:

var num = [1, 2, 3, 4, 5];

我们想要删除第4号, 你可以简单地使用下面的代码:

num.splice(num.indexOf(4), 1); // num will be [1, 2, 3, 5];

如果您正在重复使用此函数,请写入一个可重复使用的函数,该函数将附于原土类似以下的数组函数 :

Array.prototype.remove = Array.prototype.remove || function(x) {
  const i = this.indexOf(x);
  if(i===-1)
      return;
  this.splice(i, 1); // num.remove(5) === [1, 2, 3];
}

但如果您有下面的数组, 而不是数组中的几个 [5] 呢?

var num = [5, 6, 5, 4, 5, 1, 5];

我们需要一个循环来检查它们, 但是一个更容易和更有效的方法是使用内置的 JavaScript 函数, 所以我们写一个函数, 使用下面这样的过滤器 :

const _removeValue = (arr, x) => arr.filter(n => n!==x);
//_removeValue([1, 2, 3, 4, 5, 5, 6, 5], 5) // Return [1, 2, 3, 4, 6]

还有第三方图书馆,如Lodash 或Goint, 也帮助你这样做。更多信息,请参看 Lodash _. pull,_. pullAt 或_。

您可以简单地将删除函数添加到数组原体Type

类似的东西 :

Array.prototype.remove = function(value) {
  return  this.filter(item => item !== value)
}

Array.prototype.remove = function(value) {
  return  this.filter(item => item !== value)
}

let array = [10,15,20]

result = array.remove(10)
console.log(result)