Javascript 如何按值从数组中删除项目?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3954438/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:49:56  来源:igfitidea点击:

How to remove item from array by value?

javascriptarrays

提问by MacMac

Is there a method to remove an item from a JavaScript array?

有没有一种方法可以从 JavaScript 数组中删除一个项目?

Given an array:

给定一个数组:

var ary = ['three', 'seven', 'eleven'];

I would like to do something like:

我想做类似的事情:

removeItem('seven', ary);

I've looked into splice()but that only removes by the position number, whereas I need something to remove an item by its value.

我已经研究过,splice()但只能按位置号删除,而我需要一些东西来按其值删除项目。

采纳答案by kennebec

This can be a global function or a method of a custom object, if you aren't allowed to add to native prototypes. It removes all of the items from the array that match any of the arguments.

如果不允许添加到本机原型,这可以是全局函数或自定义对象的方法。它从数组中删除与任何参数匹配的所有项目。

Array.prototype.remove = function() {
    var what, a = arguments, L = a.length, ax;
    while (L && this.length) {
        what = a[--L];
        while ((ax = this.indexOf(what)) !== -1) {
            this.splice(ax, 1);
        }
    }
    return this;
};

var ary = ['three', 'seven', 'eleven'];

ary.remove('seven');

/*  returned value: (Array)
three,eleven
*/

To make it a global-

使其成为全球

function removeA(arr) {
    var what, a = arguments, L = a.length, ax;
    while (L > 1 && arr.length) {
        what = a[--L];
        while ((ax= arr.indexOf(what)) !== -1) {
            arr.splice(ax, 1);
        }
    }
    return arr;
}
var ary = ['three', 'seven', 'eleven'];
removeA(ary, 'seven');


/*  returned value: (Array)
three,eleven
*/

And to take care of IE8 and below-

并照顾 IE8 及以下 -

if(!Array.prototype.indexOf) {
    Array.prototype.indexOf = function(what, i) {
        i = i || 0;
        var L = this.length;
        while (i < L) {
            if(this[i] === what) return i;
            ++i;
        }
        return -1;
    };
}

回答by SLaks

You can use the indexOfmethodlike this:

你可以使用这样的indexOf方法

var index = array.indexOf(item);
if (index !== -1) array.splice(index, 1);

Note: You'll need to shim it for IE8 and below

注意您需要为 IE8 及以下版本填充它

var array = [1,2,3,4]
var item = 3

var index = array.indexOf(item);
if (index !== -1) array.splice(index, 1);

console.log(array)

回答by John Williams

A one-liner will do it,

一个单线就可以了,

var ary = ['three', 'seven', 'eleven'];

// Remove item 'seven' from array
var filteredAry = ary.filter(function(e) { return e !== 'seven' })
//=> ["three", "eleven"]

// In ECMA6 (arrow function syntax):
var filteredAry = ary.filter(e => e !== 'seven')

This makes use of the filterfunction in JS. It's supported in IE9 and up.

这利用了JS中的过滤器功能。它在 IE9 及更高版本中受支持。

What it does (from the doc link)

它的作用(来自文档链接)

filter() calls a provided callback function once for each element in an array, and constructs a new array of all the values for which callback returns a value that coerces to true. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values. Array elements which do not pass the callback test are simply skipped, and are not included in the new array.

filter() 为数组中的每个元素调用一次提供的回调函数,并构造一个新数组,其中包含回调返回强制为 true 的值的所有值。仅对已分配值的数组索引调用回调;不会为已删除或从未分配值的索引调用它。未通过回调测试的数组元素将被简单地跳过,并且不包含在新数组中。

So basically, this is the same as all the other for (var key in ary) { ... }solutions, except that the for inconstruct is supported as of IE6.

所以基本上,这与所有其他for (var key in ary) { ... }解决方案相同,只是for in从 IE6 开始支持该构造。

Basically, filter is a convenience method that looks a lot nicer (and is chainable) as opposed to the for inconstruct (AFAIK).

基本上,过滤器是一种方便的方法,与for in构造(AFAIK)相比,它看起来更好(并且可以链接)。

回答by vatsal

You can use underscore.js. It really makes things simple.

您可以使用underscore.js。它真的让事情变得简单。

For example, with this:

例如,与此:

var result = _.without(['three','seven','eleven'], 'seven');

And resultwill be ['three','eleven'].

并且result['three','eleven']

In your case the code that you will have to write is:

在您的情况下,您必须编写的代码是:

ary = _.without(ary, 'seven')

It reduces the code that you write.

它减少了您编写的代码。

回答by gadlol

Check out this way:

看看这个:

for(var i in array){
    if(array[i]=='seven'){
        array.splice(i,1);
        break;
    }
}

and in a function:

并在一个函数中:

function removeItem(array, item){
    for(var i in array){
        if(array[i]==item){
            array.splice(i,1);
            break;
        }
    }
}

removeItem(array, 'seven');

回答by AmerllicA

You can do it with these two ways:

您可以通过以下两种方式做到这一点:

const arr = ['1', '2', '3', '4'] // we wanna delete number "3"
  1. The first way:

    arr.indexOf('3') !== -1 && arr.splice(arr.indexOf('3'), 1)
    
  2. The second way (ES6) specially without mutate:

    const newArr = arr.filter(e => e !== '3')
    
  1. 第一种方式:

    arr.indexOf('3') !== -1 && arr.splice(arr.indexOf('3'), 1)
    
  2. 第二种方式(ES6)特别没有 mutate

    const newArr = arr.filter(e => e !== '3')
    

回答by CorayThan

Here's a version that uses jQuery's inArray function:

这是一个使用 jQuery 的inArray 函数的版本:

var index = $.inArray(item, array);
if (index != -1) {
    array.splice(index, 1);
}

回答by Hymankobec

The simplest solution is:

最简单的解决方案是:

array - array for remove some element valueForRemove; valueForRemove - element for remove;

数组 - 用于删除某些元素 valueForRemove 的数组;valueForRemove - 删除元素;

array.filter(arrayItem => !array.includes(valueForRemove));

More simple:

更简单:

array.filter(arrayItem => arrayItem !== valueForRemove);

No pretty, but works:

不漂亮,但有效:

array.filter(arrayItem => array.indexOf(arrayItem) != array.indexOf(valueForRemove))

No pretty, but works:

不漂亮,但有效:

while(array.indexOf(valueForRemove) !== -1) {
  array.splice(array.indexOf(valueForRemove), 1)
}

P.S. The filter() method creates a new array with all elements that pass the test implemented by the provided function. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

PS filter() 方法创建一个新数组,其中包含通过提供的函数实现的测试的所有元素。请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

回答by Kld

var index = array.indexOf('item');

if(index!=-1){

   array.splice(index, 1);
}

回答by Matee Gojra

Simply

简单地

var ary = ['three', 'seven', 'eleven'];
var index = ary.indexOf('seven'); // get index if value found otherwise -1

if (index > -1) { //if found
  ary.splice(index, 1);
}