如何在 JavaScript 中從陣列中移除特定專案
我們被要求為陣列編寫一個 Array.prototype.remove() 函式。它接受一個引數;它要麼是一個回撥函式,要麼是陣列的可能元素。如果它是一個函式,則該函式的返回值應被視為陣列的可能元素,並且我們必須在就地陣列中查詢並刪除該元素,並且如果找到並刪除該元素,函式應返回 true,否則應該返回 false。
因此,讓我們編寫此函式的程式碼 −
示例
const arr = [12, 45, 78, 54, 1, 89, 67]; const names = [{ fName: 'Aashish', lName: 'Mehta' }, { fName: 'Vivek', lName: 'Chaurasia' }, { fName: 'Rahul', lName: 'Dev' }]; const remove = function(val){ let index; if(typeof val === 'function'){ index = this.findIndex(val); }else{ index = this.indexOf(val); }; if(index === -1){ return false; }; return !!this.splice(index, 1)[0]; }; Array.prototype.remove = remove; console.log(arr.remove(54)); console.log(arr); console.log(names.remove((el) => el.fName === 'Vivek')); console.log(names);
輸出
控制檯中的輸出將為 −
true [ 12, 45, 78, 1, 89, 67 ] true [ { fName: 'Aashish', lName: 'Mehta' }, { fName: 'Rahul', lName: 'Dev' } ]
廣告