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

array.remove(value);

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


当前回答

[2,3,5].filter(i => ![5].includes(i))

其他回答

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');

您可以在 JavaScript 以多种方式完成此任务

如果您知道该值的索引 : 您可以在此情况下使用 spolice var arr = [1, 2, 3,4] / / / / 假设我们有该索引, 来源于某些 API let index = 2; // spolice 是一种破坏性的方法, 并修改原始数组 arr. spice (2, 1) 。 如果您没有该索引, 并且只有该值 : 您可以在此情况下使用过滤器 / / let's remove '2', 例如 arr = arr. filter (( 值) 返回值 $ ( = 2); }

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)

var 数组 = [2, 5, 9]; var res = 数组.spliice( array. findindIndex( x x x = = = 5) 1; 控制台. log( res) (sres)

使用 Array. findindindex, 我们可以减少代码行数。

开发者.mozilla.org

如果您在数组中有复杂的对象, 您可以使用过滤器 。 在 $. in Array 或 tray. splice 不容易使用的情况下 。 特别是如果对象在数组中可能是浅的 。

例如,如果您有一个带有 Id 字段的对象,而您想要从数组中删除该对象:

this.array = this.array.filter(function(element, i) {
    return element.id !== idToRemove;
});