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

array.remove(value);

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


当前回答

尝试使用此代码filter方法,您可以从数组中删除任何特定项。

let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
function removeItem(arr, value) {
  return arr.filter(function (ele) {
    return ele !== value;
  });
}
console.log(removeItem(arr, 6));

其他回答

没必要用indexOfsplice。但是,如果只想要删除一个元素的发生,则该元素的性能会更好。

查找并移动( 移动) :

function move(arr, val) {
  var j = 0;
  for (var i = 0, l = arr.length; i < l; i++) {
    if (arr[i] !== val) {
      arr[j++] = arr[i];
    }
  }
  arr.length = j;
}

使用使用indexOfsplice(指数):

function indexof(arr, val) {
  var i;
  while ((i = arr.indexOf(val)) != -1) {
    arr.splice(i, 1);
  }
}

仅使用splice(恶作剧):

function splice(arr, val) {
  for (var i = arr.length; i--;) {
    if (arr[i] === val) {
      arr.splice(i, 1);
    }
  }
}

带有 1000 元素的阵列( 平均超过 10,000 次运行) 的节点js 上的运行时间 :

指数指数慢于移动移动即使通过取消要求indexOf复盘,它的表现比移动移动.

Remove all occurrences:
    move 0.0048 ms
    indexof 0.0463 ms
    splice 0.0359 ms

Remove first occurrence:
    move_one 0.0041 ms
    indexof_one 0.0021 ms

如果您想要删除删除位置的新数组,您可以总是删除特定元素,并过滤该数组。它可能需要扩展矩阵对象对于不执行过滤法的浏览器来说,但从长远来看,它更容易,因为你所做的只是这个:

var my_array = [1, 2, 3, 4, 5, 6];
delete my_array[4];
console.log(my_array.filter(function(a){return typeof a !== 'undefined';}));

它应显示[1, 2, 3, 4, 6].

const arr = [1, 2, 3, 4, 5]
console.log(arr) // [ 1, 2, 3, 4, 5 ]

假设你想从Arr删除3号

const newArr = arr.filter(w => w !==3)
console.log(newArr) // [ 1, 2, 4, 5 ]

OK,OK, OK, OK, OK, OK, OK, OK, OK,OK, OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,例如,您有下面的数组:

var num = [1, 2, 3, 4, 5];

我们想要删除第4号, 你可以简单地使用下面的代码:

num.splice(num.indexOf(4), 1); // num will be [1, 2, 3, 5];

如果您正在重复使用此函数,请写入一个可重复使用的函数,该函数将附于原土类似以下的数组函数 :

Array.prototype.remove = Array.prototype.remove || function(x) {
  const i = this.indexOf(x);
  if(i===-1)
      return;
  this.splice(i, 1); // num.remove(5) === [1, 2, 3];
}

但如果您有下面的数组, 而不是数组中的几个 [5] 呢?

var num = [5, 6, 5, 4, 5, 1, 5];

我们需要一个循环来检查它们, 但是一个更容易和更有效的方法是使用内置的 JavaScript 函数, 所以我们写一个函数, 使用下面这样的过滤器 :

const _removeValue = (arr, x) => arr.filter(n => n!==x);
//_removeValue([1, 2, 3, 4, 5, 5, 6, 5], 5) // Return [1, 2, 3, 4, 6]

还有第三方图书馆,如Lodash 或Goint, 也帮助你这样做。更多信息,请参看 Lodash _. pull,_. pullAt 或_。

Array.prototype.removeByValue = function (val) {
  for (var i = 0; i < this.length; i++) {
    if (this[i] === val) {
      this.splice(i, 1);
      i--;
    }
  }
  return this;
}

var fruits = ['apple', 'banana', 'carrot', 'orange'];
fruits.removeByValue('banana');

console.log(fruits);
// -> ['apple', 'carrot', 'orange']