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

array.remove(value);

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


当前回答

约翰·里维格( 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);

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

其他回答

我还有一个从阵列中移除的好办法:

var words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(word => word.length > 6);

console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

var index,
    input = [1,2,3],
    indexToRemove = 1;
    integers = [];

for (index in input) {
    if (input.hasOwnProperty(index)) {
        if (index !== indexToRemove) {
            integers.push(result); 
        }
    }
}
input = integers;

此解决方案将需要一系列输入, 并将通过输入查找要删除的值。 这将在整个输入数组中循环, 结果将是第二个已经删除了特定索引的数组整数组。 然后将整数组复制到输入数组中 。

检查一下这个代码 每个代码都有效主浏览器.

remove_item = function(arr, value) {
 var b = '';
 for (b in arr) {
  if (arr[b] === value) {
   arr.splice(b, 1);
   break;
  }
 }
 return arr;
};

var array = [1,3,5,6,5,9,5,3,55]
var res = remove_item(array,5);
console.log(res)

你可以轻而易举地用过滤过滤器方法 :

function remove(arrOriginal, elementToRemove){
    return arrOriginal.filter(function(el){return el !== elementToRemove});
}
console.log(remove([1, 2, 1, 0, 3, 1, 4], 1));

这将清除数组中的所有元素, 并且运行速度比sliceindexOf.

以下方法将从数组中删除给定值的所有条目,而不创建新数组,且只有一个迭代,即超快它在古代因特网探索者 5.5浏览器 :

function removeFromArray(arr, removeValue) {
  for (var i = 0, k = 0, len = arr.length >>> 0; i < len; i++) {
    if (k > 0)
      arr[i - k] = arr[i];

    if (arr[i] === removeValue)
      k++;
  }

  for (; k--;)
    arr.pop();
}

var a = [0, 1, 0, 2, 0, 3];

document.getElementById('code').innerHTML =
  'Initial array [' + a.join(', ') + ']';
//Initial array [0, 1, 0, 2, 0, 3]

removeFromArray(a, 0);

document.getElementById('code').innerHTML +=
  '<br>Resulting array [' + a.join(', ') + ']';
//Resulting array [1, 2, 3]
<code id="code"></code>