简体   繁体   中英

Array function with IndexOf() and splice()

I have an array filled with fridge items. I am trying to find the index of particular items and then splice them out of the array and then return the item and console.log the remaining items in the fridge. I have no clue why it isn't working. I have tried several different variations and I have tried looking at other similar answers for this question. Any advice or help is much appreciated.

fridge = ["milk", "cheese", "butter"];

function removeItemFromFridge(item) {
  
  if (item.indexOf()) {
    fridge.splice(item);
    return item;
  } else {
    return null;
  }
}
removeItemFromFridge("milk");
removeItemFromFridge("butter");

console.log(fridge);

If fridge is a value we can replace entirely instead of modifying the existing array, you can use array.filter() instead.

function removeItemFromFridge(item) {
  fridge = fridge.filter(v => v !== item)
}

Otherwise, if you do want to preserve that same array, you can find the item index and splice it off.

function removeItemFromFridge(item) {
  const index = fridge.indexOf(item);
  if (index !== -1) fridge.splice(index, 1)
}

Also, doing a return is not needed since your caller isn't using the returned value.

indexOf finds the first index that matches the given value in the array, if no such value is present it returns -1. for splice you specify the first index from where you want to start deleting and in the second argument you pass the number of element you want to delete starting from given index in first argument. I think you want to do it like this way

let fridge = ["milk", "cheese", "butter"];

function removeItemFromFridge(item) {
  const index = fridge.indexOf(item);
  
  if (index > -1 ) {
    fridge.splice(index, 1);
    return item;
  } else {
    return null;
  }
}
removeItemFromFridge("milk");
removeItemFromFridge("butter");

console.log(fridge);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM