如何检查此函数是否为真或 return 是否为空数组(如果为假)?

How can I check this function for truthy or return an empty array if falsy?

我正在看这个作业,我的问题是最后加粗的部分:

// Do not edit the code below.
var myGroceryList = ['chips', 'pizza', 'hotpockets', 'MtnDew', 'corndogs'];
// Do not edit the code above.

Here we're going to write a function that mimics going shopping and checking things off of our grocery list and adding new items to our list.

Write a function called removeItem that is given two arguments, the first is myGroceryList, and the second is an item to remove from myGroceryList. If the second argument (or the item to add or remove) matches an item in myGroceryList, remove that item from the your grocery list and return the new, updated grocery list.

Once you do that, write another function called addItem that is given two arguments, the first is myGroceryList and the second is an item to add to your grocery list. In addItem add the item you passed in to myGroceryList then return the new, updated grocery list.

In both removeItem and addItem check to see if the 'myGroceryList' and 'item' arguments are truthy. If they are not, return an empty array.

Here are some examples of calling your functions and what should be returned:

removeItem(myGroceryList, 'chips') --> ['pizza', 'hotpockets', 'MtnDew', 'corndogs'];
addItem(myGroceryList, 'Jerky') --> ['pizza', 'hotpockets', 'MtnDew', 'corndogs', 'Jerky'];
removeItem(myGroceryList) --> [];
addItem() --> [];

这是我的代码:

removeItem=(myGroceryList,item)=>{
   return myGroceryList.filter((thing)=>{
      return thing != item
   })
}

addItem=(myGroceryList, item)=>{
   myGroceryList.push(item);
   return myGroceryList;
} 

我怎样才能让它的最后一步起作用?

您可以立即检查是否为假和 return 一个空数组,而不是检查是否为真。

   addItem=(myGroceryList, item) => {
      if(!myGroceryList) { return [] }
      myGroceryList.push(item);
      return myGroceryList;
   }

只需添加一个 if 来验证两个参数的真实性:

removeItem=(myGroceryList,item)=>{
   if (!myGroceryList || !item) return [];
   return myGroceryList.filter((thing)=>{
      return thing != item
   })
}

不改变参数

当您被要求 return 新列表时,您很好地使用了 filter 并且没有改变原始列表。但是你最好将相同的原则应用到 addItem,它也应该是 return 新列表,因此最好不要改变给定的列表:

addItem=(myGroceryList, item)=>{
   if (!myGroceryList || !item) return [];
   return myGroceryList.concat(item); // don't use push, but concat
} 

或者...改变参数?

但是,在作业末尾给出的示例代码 没有使用函数的 return 值 (控制台报告它除外) ,从第二次调用中我们可以看到,“筹码”实际上已经从 给定 的列表中删除给 removeItem.

的第一次调用

所以这意味着你必须让你的函数具有 side-effects.

在这种情况下,您不应使用 filterconcat,而应将第一个函数更改为使用 splice:

removeItem=(myGroceryList,item)=>{
   if (!myGroceryList || !item) return [];
   let i = myGroceryList.indexOf(item);
   if (i >= 0) myGroceryList.splice(i, 1); // mutate the list
   return myGroceryList;
}

...并且您将使用带有 push 的版本用于 addItem:

addItem=(myGroceryList, item)=>{
   if (!myGroceryList || !item) return [];
   myGroceryList.push(item); // mutate...
   return myGroceryList;
}