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

array.remove(value);

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


当前回答

从数组中删除一个特定元素, 可以在过滤器选项的一行内完成, 并得到所有浏览器的支持 :https://caniuse.com/#search=filter%20array

function removeValueFromArray(array, value) {
    return array.filter(e => e != value)
}

我在这里测试了这个函数 :https://bit.dev/joshk/jotils/remove-value-from-array/~code#test.ts

其他回答

ES6且无突变:(2016年10月)

const removeByIndex = (list, index) =>
      [
        ...list.slice(0, index),
        ...list.slice(index + 1)
      ];
         
output = removeByIndex([33,22,11,44],1) //=> [33,11,44]
      
console.log(output)

  • 弹出 - 从矩阵结束处删除
  • - 从数组的开头删除
  • 复项 - 从特定的数组索引中删除
  • - 过滤器允许您程序化地从数组中删除元素

您可以使用ES6. 例如,在此情况下删除值“ 3” :

var array=['1','2','3','4','5','6']
var newArray = array.filter((value)=>value!='3');
console.log(newArray);

产出:

["1", "2", "4", "5", "6"]

您可以为此创建一个原型。只需通过数组元素和您想要从数组元素中删除的值:

Array.prototype.removeItem = function(array,val) {
    array.forEach((arrayItem,index) => {
        if (arrayItem == val) {
            array.splice(index, 1);
        }
    });
    return array;
}
var DummyArray = [1, 2, 3, 4, 5, 6];
console.log(DummyArray.removeItem(DummyArray, 3));

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

arr.splice(0,1)

console.log(arr)

产出[2、3、4、5];