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

array.remove(value);

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


当前回答

从带有数组元素的阵列列表中获取阵列和索引 从使用地图toint () 和 Toarray () 方法的阵列新阵列中删除 使用删除 () 方法删除具体索引元素 返回格式化的阵列

其他回答

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

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

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

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

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

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

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

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

数组. remove( 位置) ;

Array. prototype. remove = 函数 (pos) {此. splice(pos, 1);} var arr = ["a", "b", "c", "d", "e"]; arr. remove(2); // 移除"c" 控制台.log(ar);

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

array.erase(element);

Array. prototype. erase = 函数( el) { let p = this. indexof (el); // indexof use prettical equality () { this. spliice (p, 1);}} var ar ar = ["a", "b", "c", "d", "e"; arr.erase (c"); 控制台. log (a) ;

我测试了复数和过滤器 看哪个更快:

let someArr = [... Array(999999). keys ()] 控制台.time(“ filter” ) someArr. filter(x x = = = = = 666666) 控制台.timeEnd(“ filter ” ) 控制台.time(“ splice by indexof ” ) someArr. splice( some Arr. indexof( 6666), 1) 控制台.timeEnd( “ splice by indexof ” )

在我的机器上, 复数会更快。 这有道理, 因为复数只编辑一个已有的数组, 而过滤器会创建一个新的数组 。

因此,过滤器在逻辑上是更清洁的(更容易阅读),并且更适合使用不可改变状态的编码风格。因此,由你来决定你是否想做出这种权衡。