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

array.remove(value);

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


当前回答

var 数组 = [2, 5, 9]; var res = 数组.spliice( array. findindIndex( x x x = = = 5) 1; 控制台. log( res) (sres)

使用 Array. findindindex, 我们可以减少代码行数。

开发者.mozilla.org

其他回答

大部分答案都用...

循环的索引和组合删除过滤器

虽然所有解决方案都应该采用这些方法,但我想我们可以使用弦操纵。

需要注意的关于这一解决办法的要点 -- --

这将在数据中留下漏洞( 可以通过额外的过滤器将其移除 ) 此解决方案不仅适用于原始搜索值, 也适用于对象 。

诀窍是...

字符串字符串返回分隔符上的分解数据,以空字符串替换输入数据集中的搜索值。

    remove = (input, value) => {
        const stringVal = JSON.stringify(value);
        const result = JSON.stringify(input)

        return result.replace(stringVal, "").split(",");
    }

本文创建了一个测试对象和数字的 JSF 中心- https://jsfidle.net/4t7zhkce/33/

检查小提琴中的移除方法 。

删除上次的元素

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

从数组中删除一个特定元素, 可以在过滤器选项的一行内完成, 它得到所有浏览器的支持 : 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

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

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

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

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

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

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