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

array.remove(value);

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


当前回答

以下方法将从数组中删除给定值的所有条目,而不创建新数组,且只有一个迭代,即超快它在古代因特网探索者 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>

其他回答

这取决于你是否想保持一个空位。

如果你(如果)do do do 做想要一个空位 :

array[index] = undefined;

如果你(如果)不要想要一个空位 :

//To keep the original:
//oldArray = [...array];

//This modifies the array.
array.splice(index, 1);

如果您需要该项的值, 您可以保存返回的数组元素 :

var value = array.splice(index, 1)[0];

如果您要在数组两端的两端删除,可以使用array.pop()最后一个或最后一个array.shift()对第一个项目(两者都返回项目的价值) 。

如果你不知道项目的索引,你可以使用array.indexOf(item)以获得(在if()获得一个或一个while()以获得全部)))。array.indexOf(item)返回索引或-1尚未找到 。

尝试使用删除运算符

例如:

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 removeFromArrayPolyfill() {
      if (window.Array.prototype.remove) return;
    
      Array.prototype.remove = function (value) {
        if (!this.length || !value) return;
    
        const indexOfValue = this.indexOf(value);
    
        if (indexOfValue >= 0) {
          this.splice(indexOfValue, 1);
        }
      };
    })();
    
    // testing polyfill
    const nums = [10, 20, 30];
    nums.remove(20);
    console.log(nums);//[10,30]
 const Delete = (id) => {
      console.log(id)
     var index = Array.map(function(e){
      return e.id;
     
     }).indexOf(id);
     Array.splice(index,1);
     
}

我建议删除一个使用删除和过滤的阵列项目:

var arr = [1,2,3,4,5,5,6,7,8,9];
delete arr[5];
arr = arr.filter(function(item){ return item != undefined; });
//result: [1,2,3,4,5,6,7,8,9]

console.log(arr)

因此,我们只能删除一个特定的数组项目,而不是所有具有相同价值的项目。