JS:按值从数组中删除第一个元素

Kat*_*man 1 javascript arrays filter

我有一个数组:

arr = [50, 40, 50, 50];
Run Code Online (Sandbox Code Playgroud)

我需要删除等于50的第一个元素,并且不要触摸另一个。此代码仅返回[40]

arr = arr.filter(function(e) {return e !== 50}) // [40]
Run Code Online (Sandbox Code Playgroud)

但是我需要

arr = arr.somefunction(function(e) {return e !== 50}) // [40, 50, 50]
Run Code Online (Sandbox Code Playgroud)

我将不胜感激。

Mah*_*Ali 5

您可以使用findIndexsplice()

let arr = [50, 40, 50, 50];
arr.splice(arr.findIndex(a => a === 50), 1);
console.log(arr)
Run Code Online (Sandbox Code Playgroud)

如果prototype在Array 上需要它,则可以定义自定义方法。

function removeFirst(cb){
  for(let i = 0;i<this.length;i++){
    if(cb(this[i],i,this)){
      return this.slice(0,i).concat(this.slice(i+1));
    }
  }
  return this;
}

Object.defineProperty(Array.prototype,'removeFirst',{
  value:removeFirst
})

let arr = [50,40,50,50];
let res = arr.removeFirst(x => x === 50);
console.log(res)
Run Code Online (Sandbox Code Playgroud)