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

array.remove(value);

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


当前回答

用于解决多个浏览器的问题。 如果存在的话, 它会使用在建浏览器的方法。 如果没有这些方法, 则使用自己的自定义方法。 如果像旧版的互联网探索者一样, 它会使用自己的自定义方法 。

从数组中删除元素( 从网站) 的简单示例 :

_.without([1, 2, 1, 0, 3, 1, 4], 0, 1); // => [2, 3, 4]

其他回答

检查一下这个代码 每个主要浏览器都使用这个代码

删除项目 = 函数( rr) { varb = ' ; 对于 (b in arr) { 如果 (ar[ b] { { { { { rr. splice( b, 1); 折断 ; } rr; } 返回 arr; } } 返回 arr; } ; var 数组 = [1, 5,6, 9, 5, 5, 355] var res = mote_ item( arry, 5); 控制台. log( res) = [1, 3, 5, 9, 5, 5, 55, Var Res = dection_ item( arry, 5); 控制台 log( res)

尝试使用删除运算符删除数组元素

例如:

const arr = [10, 20, 30, 40, 50, 60];
delete arr[2]; // It will Delete element present at index 2
console.log( arr ); // [10, 20, undefined , 40, 50, 60]

注意: 使用删除运算符将会在数组中留下空空空/ 空洞。 它不会提醒数组的长度。 要在元素被删除时更改数组的长度, 请使用复数法 。

希望这能解决你所有的问题

我知道已经有很多答案了, 但其中许多答案似乎都使问题复杂化了。 这是一个简单的、循环的删除所有关键实例的方法- 在找不到索引之前自呼自用。 是的, 它只在有索引的浏览器中起作用, 但是它很简单, 并且很容易被多填 。

独立职能

function removeAll(array, key){
    var index = array.indexOf(key);

    if(index === -1) return;

    array.splice(index, 1);
    removeAll(array,key);
}

原型方法

Array.prototype.removeAll = function(key){
    var index = this.indexOf(key);

    if(index === -1) return;

    this.splice(index, 1);
    this.removeAll(key);
}

John Resig张贴了很好的执行:

// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};

如果您不想扩展一个全球对象, 可以做一些类似的东西,

// Array Remove - By John Resig (MIT Licensed)
Array.remove = function(array, from, to) {
    var rest = array.slice((to || from) + 1 || array.length);
    array.length = from < 0 ? array.length + from : from;
    return array.push.apply(array, rest);
};

但我之所以张贴这篇文章,主要是为了提醒用户不要采取该页(2007年12月14日)评论中建议的其他实施方式:

Array.prototype.remove = function(from, to) {
  this.splice(from, (to=[0, from || 1, ++to - from][arguments.length]) < 0 ? this.length + to : to);
  return this.length;
};

它一开始似乎效果良好,但经过一个痛苦的过程,我发现它在试图删除数组中第二至最后一个元素时失败了。例如,如果您有一个 10 元素数组,并且试图用这个来删除第九元素:

myArray.remove(8);

我不知道为什么 但我确认约翰的原创执行没有问题

您可以使用过滤器方法轻松操作 :

函数删除( 收到原件, 元素将移动) { 返回 原件 。 filter( 职能 ) { return el ! === 元素 Toremove} ;} 控制台. log (remove ([ 1, 1, 1, 0, 3, 1, 4], 1 ) ;

这将清除数组中的所有元素, 并且比切片和索引的组合效果更快 。