【问题标题】:Array function with IndexOf() and splice()带有 IndexOf() 和 splice() 的数组函数
【发布时间】:2021-04-23 22:26:11
【问题描述】:

我有一个装满冰箱物品的数组。我试图找到特定项目的索引,然后将它们从数组中拼接出来,然后返回项目并 console.log 冰箱中的剩余项目。 我不知道为什么它不起作用。我尝试了几种不同的变体,并尝试查看此问题的其他类似答案。非常感谢任何建议或帮助。

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 (item.indexOf()) {??不应该是if (fridge.indexOf(item)) {吗?这不会解决这个问题,还有更多问题..
  • 您可以使用Array的filter方法来删除特定的项目。
  • @IhorTkachuk,当然,从技术上讲,filter 不会从数组中删除项目,它会创建一个新数组。
  • @Wyck 但是,修改外部范围是不好的做法。
  • 这能回答你的问题吗? How can I remove a specific item from an array?

标签: javascript arrays function indexof splice


【解决方案1】:

indexOf 在数组中找到与给定值匹配的第一个索引,如果不存在这样的值,则返回 -1。对于 splice,您指定要从其中开始删除的第一个索引,并在第二个参数中传递要从第一个参数中的给定索引开始删除的元素数。 我想你想这样做

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);

【讨论】:

  • 非常感谢。通过查看您的答案,我现在知道我做错了什么。它也很有效。非常感谢。
【解决方案2】:

如果fridge 是一个我们可以完全替换而不是修改现有数组的值,则可以使用array.filter() 代替。

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

否则,如果您确实想保留相同的数组,您可以找到项目索引并将其拼接掉。

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

另外,不需要执行return,因为您的调用者没有使用返回值。

【讨论】:

  • 你写过 item.indexOf(item) ,怎么写对了,不应该是冰箱.indexOf(item)吗?
  • 是的,应该是这样。我只是把我上次吃的东西放进去。我原来有它,然后开始玩它,忘记把它改回冰箱.indexOf(item)
  • 非常感谢。你们都帮了大忙。
猜你喜欢
  • 2022-01-26
  • 2019-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-11
  • 2011-04-09
  • 2014-08-30
  • 1970-01-01
相关资源
最近更新 更多