我有一个数组:
arr = [50, 40, 50, 50];
我需要删除第一个元素,它等于 50 并且不要碰其他元素。
此代码仅返回 [40]
。
arr = arr.filter(function(e) {return e !== 50}) // [40]
但是我需要
arr = arr.somefunction(function(e) {return e !== 50}) // [40, 50, 50]
如有任何帮助,我将不胜感激。
最佳答案
您可以使用findIndex
和splice()
let arr = [50, 40, 50, 50];
arr.splice(arr.findIndex(a => a === 50), 1);
console.log(arr)
如果您在 Array 的 prototype
上需要它,那么您可以定义您的自定义方法。
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)
关于javascript - JS : delete first element from array by value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56365514/