在 freecodecamp 里做到一道题,想了一圈,看答案的时候发现解法可以十分简单。
-
题干: You will be provided with an initial array (the first argument in the
destroyerfunction), followed by one or more arguments. Remove all elements from the initial array that are of the same value as these arguments. -
示例:
destroyer([1, 2, 3, 1, 2, 3], 2, 3)should return[1, 1].destroyer([3, 5, 1, 2, 2], 2, 3, 5)should return[1].
-
答案:
function destroyer(arr,...del) { let newArr = []; newArr = arr.filter(item => !del.includes(item)); return newArr; } -
再精简一下:
function destroyer(arr,...del) { return arr.filter(item => !del.includes(item)); } -
思路:
- 过滤数组。如何过滤呢?
- 对原数组中的每一个元素一一验证来进行过滤。如何验证呢?
- 验证该元素是不是被包含在
del数组中,del数组说明了需要被删除的元素。此时,includes就十分巧妙地发挥了这个验证作用。如果没有,则通过验证,被过滤出。
- 验证该元素是不是被包含在
- 对原数组中的每一个元素一一验证来进行过滤。如何验证呢?
- 过滤数组。如何过滤呢?