JS數組刪除某個元素的方法實現的代碼:
使用數組迭代
function removeElement(arr, ele){
var result = [];
if(arr instanceof Array){
if(ele instanceof Array){
result = arr.filter(function(item){
var isInEle = ele.some(function(eleItem){
return item === eleItem;
});
return !isInEle
})
}else{
result = arr.filter(function(item){
return item !== ele
})
}
}else{
console.log('parameter error of function removeElement');
}
return result;
}
功能測試
使用常規的數組方法splice
首先可以給js的數組對象定義一個函數,用於查找指定的元素在數組中的位置,即索引,代碼爲:
Array.prototype.indexOf = function(val) {
for (var i = 0; i < this.length; i++) {
if (this[i] == val) return i;
}
return -1;
};
然後使用通過得到這個元素的索引,使用js數組自己固有的函數去刪除這個元素:
Array.prototype.remove = function(val) {
var index = this.indexOf(val);
if (index > -1) {
this.splice(index, 1);
}
};