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

array.remove(value);

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


当前回答

主要有两种办法:

  1. 复数(): anArray.splice(index, 1);

     let fruits = ['Apple', 'Banana', 'Mango', 'Orange']
     let removed = fruits.splice(2, 1);
     // fruits is ['Apple', 'Banana', 'Orange']
     // removed is ['Mango']
    
  2. 删除删除: delete anArray[index];

     let fruits = ['Apple', 'Banana', 'Mango', 'Orange']
     let removed = delete fruits(2);
     // fruits is ['Apple', 'Banana', undefined, 'Orange']
     // removed is true
    

使用时要小心delete用于对数组的数组。它有利于删除对象的属性,但对于数组则不那么好。最好使用splice用于数组。

请注意,当使用delete对于一个数组,您可能会获得错误的结果anArray.length换句话说,delete将会删除元素, 但它不会更新长度属性的值 。

使用删除后,也可以期望在索引编号上出现空洞,例如,最后可能会有第1、3、4、8、9和11号指数,而之前的长度与使用删除时相同。for循环会崩溃, 因为索引不再是相继的 。

被迫使用delete出于某种原因,你应该使用for each需要通过数组循环时循环循环。事实上,总是避免使用索引for如果可能的话,循环。这样代码就会更稳健,更不易遇到指数问题。

其他回答

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 或_。

const newArray = oldArray.filter(item => item !== removeItem);
function array_remove(arr, index) {
    for (let i = index; i < arr.length - 1; i++) {
        arr[i] = arr[i + 1];
    }
    arr.length -= 1;
    return arr;
}
my_arr = ['A', 'B', 'C', 'D'];
console.log(array_remove(my_arr, 0));

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

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

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

尝试使用删除运算符

例如:

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]

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

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