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

array.remove(value);

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


当前回答

我找到了这个博客文章,

9 从 JavaScript 阵列中删除元素的方法 - 附加如何安全清除 JavaScript 阵列

我更喜欢使用过滤器 () :

var filtered_arr = arr.filter(function(ele){
   return ele != value;
})

其他回答

您可以使用过滤器方法轻松操作 :

函数删除( 收到原件, 元素将移动) { 返回 原件 。 filter( 职能 ) { return el ! === 元素 Toremove} ;} 控制台. log (remove ([ 1, 1, 1, 0, 3, 1, 4], 1 ) ;

这将清除数组中的所有元素, 并且比切片和索引的组合效果更快 。

如果您想要 [.].remove(el) 类似语法的语法, 和其他编程语言一样, 那么您可以添加此代码 :

// Add remove method to Array prototype
Array.prototype.remove = function(value, count=this.length) {
    while(count > 0 && this.includes(value)) {
        this.splice(this.indexOf(value), 1);
        count--;
    }
    return this;
}

用法

// Original array
const arr = [1,2,2,3,2,5,6,7];

// Remove all 2s from array
arr.remove(2); // [1,3,5,6,7]

// Remove one 2 from beginning of array
arr.remove(2, 1); // [1,2,3,2,5,6,7]

// Remove two 2s from beginning of array
arr.remove(2, 2); // [1,3,2,5,6,7]

您可以根据您的需求操控该方法 。

Array.prototype.remove = function(x) {
    var y=this.slice(x+1);
    var z=[];
    for(i=0;i<=x-1;i++) {
        z[z.length] = this[i];
    }

    for(i=0;i<y.length;i++){
        z[z.length]=y[i];
    }

    return z;
}

您可以使用 JavaScript 的标准 __ proto__ 来定义此函数。例如,

让数据 = [;] 数据 .__proto__.remove = (n) { {数据 = 数据 : blockMap ((v) ) { { 返回 v ? v : [] n? v ; 数据 = [1, 2, 3] ; 数据 = [1, 2, 3] ; 数据.remove (2); 控制台.log(数据); / / [1,3] 数据 = [a', b', c'] ; 数据.remove ('b'); 控制台.log(数据); // [a, c]

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)