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

array.remove(value);

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


当前回答

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

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

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

其他回答

您可以为此创建一个原型。只需通过数组元素和您想要从数组元素中删除的值:

Array.prototype.removeItem = function(array,val) {
    array.forEach((arrayItem,index) => {
        if (arrayItem == val) {
            array.splice(index, 1);
        }
    });
    return array;
}
var DummyArray = [1, 2, 3, 4, 5, 6];
console.log(DummyArray.removeItem(DummyArray, 3));

减少方法的利润如下:

(a) 需要按索引删除某一要素:

function remove(arr, index) {
  return arr.reduce((prev, x, i) => prev.concat(i !== index ? [x] : []), []);
}

b) 需要删除元素值(int)的元素:

function remove(arr, value) {
  return arr.reduce((prev, x, i) => prev.concat(x !== value ? [x] : []), []);
}

这样我们就可以返回一个新的阵列( 将会以酷酷的功能方式- 比使用推或组合要好得多) , 并删除元素 。

您只需要按元素或索引过滤 :

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

var result1 = num.filter((el, index) => el != 5) // for remove all 5
var result2 = num.filter((el, index) => index != 5) // for remove item with index == 5

console.log(result1);
console.log(result2);

  1. 获取数组和索引
  2. 从带有数组元素的数组列表
  3. 使用remove()方法
  4. 从使用的新数组列表的阵列数组中maptoint()toarray()方法
  5. 返回格式化的数组

如果您想要[...].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]

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