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

array.remove(value);

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


当前回答

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

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

其他回答

尝试使用此代码filter方法,您可以从数组中删除任何特定项。

let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
function removeItem(arr, value) {
  return arr.filter(function (ele) {
    return ele !== value;
  });
}
console.log(removeItem(arr, 6));

此函数从特定位置的数组中删除元素。

array.remove(position);

Array.prototype.remove = function (pos) {
    this.splice(pos, 1);
}

var arr = ["a", "b", "c", "d", "e"];
arr.remove(2); // remove "c"
console.log(arr);

如果您不知道要删除的项目的位置, 请使用这个 :

array.erase(element);

Array.prototype.erase = function(el) {
    let p = this.indexOf(el); // indexOf use strict equality (===)
    if(p != -1) {
        this.splice(p, 1);
    }
}

var arr = ["a", "b", "c", "d", "e"];
arr.erase("c");
console.log(arr);

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

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

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

从数组中删除一个特定元素, 可以在过滤器选项的一行内完成, 并得到所有浏览器的支持 :https://caniuse.com/#search=filter%20array

function removeValueFromArray(array, value) {
    return array.filter(e => e != value)
}

我在这里测试了这个函数 :https://bit.dev/joshk/jotils/remove-value-from-array/~code#test.ts

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

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