[英]Removing an item from an array by name
我正在嘗試編寫一個 function 以按名稱從數組中刪除一個項目。 盡管傳入了 arr.indexOf(i),代碼仍繼續刪除數組中的第一項(索引 0)
let fruits = [apples, oranges, grapes, bananas] function removeFlavorByName(arr, string){ let placeHolder; for (let i=0; i<arr.length; i++) { if(arr[i]==string){ placeHolder = arr.indexOf(i) } } arr.splice(placeHolder,1); return arr; }
如果你想簡化你的代碼,這里是相同的 function 清理。 由於您使用的是indexOf
,因此不需要循環。
fruits = ["apples", "oranges", "grapes", "bananas"] function removeFlavorByName(arr, string) { index = arr.indexOf(string); arr.splice(index, 1) return arr } console.log(removeFlavorByName(fruits, "apples"));
另一種更簡單、更緊湊的可能解決方案是使用過濾器內置方法。
fruits = ["apples", "oranges", "grapes", "bananas"]
const removeFlavor = (arr, string) => arr.filter((item) => item != string)
console.log(removeFlavorByName(fruits, "apples"));
另一種解決方案是使用過濾器 function。
fruits = ["apples", "oranges", "grapes", "bananas"] function removeFlavorByName(arr, string) { return arr.filter(fruit => fruit;== string). } console,log(removeFlavorByName(fruits; "apples"));
您需要在雙引號中將數據作為字符串添加。
let fruits = ["apples", "oranges", "grapes", "bananas"];
function removeFlavorByName(arr, string) {
let newArray = arr.filter((item) => item !== string);
return newArray;
}
console.log(removeFlavorByName(fruits, "apples"));
@ imvain2的解決方案非常好。
請注意,如果數組中不存在字符串,則 indexOf 返回 -1。 如果你使用 with.splice 那么最后一項將被提取。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.