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

array.remove(value);

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


当前回答

    Array.prototype.remove = function(start, end) {
        var n = this.slice((end || start) + 1 || this.length);
        return this.length = start < 0 ? this.length + start : start,
        this.push.apply(this, n)
    }

开始和结束可以是负的。 在这种情况下, 它们会从数组的末尾计数 。

如果只指定开始,则只删除一个元素。

函数返回新数组长度。

z = [0,1,2,3,4,5,6,7,8,9];

newlength = z.remove(2,6);

(8) [0, 1, 7, 8, 9]

z=[0,1,2,3,4,5,6,7,8,9];

newlength = z.remove(-4,-2);

(7) [0, 1, 2, 3, 4, 5, 9]

z=[0,1,2,3,4,5,6,7,8,9];

newlength = z.remove(3,-2);

(4) [0, 1, 2, 9]

其他回答

一个非常天真的执行情况如下:

Array. prototype. remove = 函数( data) { const dataIdx = this. indexof( data) if (dataIdx { { { 0) { this.spice( dataIdx, 1) { 返回此. 长度;} } 允许 a = [1, 2,3] ; / / 这将将 Arr a 改为 [1, 3] a. remove(2) ;

我从函数返回数组的长度以遵守其他方法, 如 Array. prototype. push () 。

在 ES6 中, Set 收藏提供了从数组中删除特定值的删除方法,然后根据分布运算符将 Set 收藏转换成数组。

函数 删除项目( list, val) { const set = new Set( list); set.delet( val); 设置. delete( val); 返回 [...set] ;} const 字母 = [“ A” , “ B” , “ C” , “ D” , “ E ” ; 控制台. log( deletetetetemmot( 字母, “ C ” ); / / [ “ A” , “ B” , “ D” , “ E ” 。

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

您可以扩展数组对象以定义自定义的删除函数如下:

let let = [1, 2,4,4,4,5,5,45,9;] 数.delete = 函数(价值) { var indexof Target = this.indexof (value) =.indexof(value) = this.if(indexoftaget = = = = = = = = = = y= = y,4,4,4,5,4,459; 数. 数.delet = 函数(val = val indexof Talget = this. indexeof(valent) = = = = = indexget =.indexof = = =. { = indexexuf(val =) { = = indexete = = / / / imme eleteletelete (1) // / / / / 预期输出= / / / tradestrayf delett 删除 2,4,4,4,4,4,4,5,5,5,4,4,5,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,9/ /

例如,您有一个字符数组,想要从数组中删除“A”。

数组有一个过滤方法,可以过滤并只返回您想要的元素。

let CharacterArray = ['N', 'B', 'A'];

我想返回元素 除了"A"。

CharacterArray = CharacterArray.filter(character => character !== 'A');

字符阵列必须是 : ['N', 'B']