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

array.remove(value);

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


当前回答

咖啡冲咖啡:

my_array.splice(idx, 1) for ele, idx in my_array when ele is this_value

其他回答

更新 :只有当您无法使用 ECMASCript 2015 (前称ES6) 时,才会推荐使用这种方法。 如果您可以使用这种方法, 其它答案则提供更清晰的落实。


这个格子在这里将解决您的问题, 并删除所有出现参数的情况, 而不是仅一个( 或指定值) 。

Array.prototype.destroy = function(obj){
    // Return null if no objects were found and removed
    var destroyed = null;

    for(var i = 0; i < this.length; i++){

        // Use while-loop to find adjacent equal objects
        while(this[i] === obj){

            // Remove this[i] and store it within destroyed
            destroyed = this.splice(i, 1)[0];
        }
    }

    return destroyed;
}

用法 :

var x = [1, 2, 3, 3, true, false, undefined, false];

x.destroy(3);         // => 3
x.destroy(false);     // => false
x;                    // => [1, 2, true, undefined]

x.destroy(true);      // => true
x.destroy(undefined); // => undefined
x;                    // => [1, 2]

x.destroy(3);         // => null
x;                    // => [1, 2]

要从数组中删除元素, 要从数组中除去元素, 组合、 过滤和删除

每个阵列都有自己的索引,它有助于用索引删除一个特定元素。

拼盘 () 方法

array.splice(index, 1);    

第一个参数是指数指数指数指数第二个是要从该索引中删除的元素数量。

因此,单一个元素,我们用1。

删除方法

delete array[index]

过滤 () 方法

如果您想要删除一个在数组中重复的元素, 那么过滤数组 :

removeAll = array.filter(e => e != elem);

何处处elem是要从数组中删除的元素。array您的数组名称。

const newArray = oldArray.filter(item => item !== removeItem);

删除上次的元素

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];

我不知道你是怎么想的array.remove(int)行为。我可以想到三种可能性 你可能想要。

在索引中删除数组的元素i:

array.splice(i, 1);

如果您想要删除带有值的每个元素number从数组 :

for (var i = array.length - 1; i >= 0; i--) {
 if (array[i] === number) {
  array.splice(i, 1);
 }
}

如果您只想在索引中生成元素i不再存在,但你不希望其它元素的索引改变:

delete array[i];