You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用indexOf()与splice()方法移除数组中冰箱物品失败的问题求助

Hey, let's break down why your fridge item removal function isn't working and fix it step by step:

Fixing Your Fridge Item Removal Logic

What's Wrong With the Current Code

  • Wrong indexOf() usage: You're calling item.indexOf() instead of fridge.indexOf(item) — the indexOf() method is for arrays, so you need to run it on your fridge array to find the position of the item you want to remove.
  • Broken existence check: indexOf() returns -1 when the item isn't found, and the index (starting at 0) when it is. A simple if (index) check will fail for items at index 0 (like "milk" in your example), because 0 is treated as falsy in JavaScript.
  • Incorrect splice() arguments: The splice() method needs at least two arguments for deletion: the starting index, and how many items to remove. Your code only passes item, which doesn't correspond to what splice() expects.

Corrected Code

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

function removeItemFromFridge(item) {
  // Get the index of the target item in the fridge array
  const itemIndex = fridge.indexOf(item);
  
  // Only proceed if the item exists in the fridge
  if (itemIndex !== -1) {
    // splice returns an array of removed items, so we grab the first element
    const removedItem = fridge.splice(itemIndex, 1)[0];
    return removedItem;
  } else {
    // Return null if the item isn't found
    return null;
  }
}

// Test the function calls
removeItemFromFridge("milk");
removeItemFromFridge("butter");

// Log the remaining items in the fridge
console.log(fridge); // Output: ["cheese"]

What Changed & Why

  1. Proper Index Lookup: fridge.indexOf(item) correctly locates where the item is stored in the array.
  2. Reliable Existence Check: Using itemIndex !== -1 ensures we don't try to remove an item that isn't there, and it doesn't miss items at index 0.
  3. Correct splice() Usage: fridge.splice(itemIndex, 1) tells JavaScript to start at the found index and remove 1 item. Since splice() returns an array of removed elements, we take the first (and only) element to get the actual item we removed.
  4. Clear Return Values: The function now returns the removed item when successful, or null if the item wasn't in the fridge — this makes the behavior predictable.

When you run this code, you'll see the remaining fridge items are just ["cheese"], which is exactly what you wanted!

内容的提问来源于stack exchange,提问作者Nicole Roberts

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 04:27:32