箭头函数与filter方法结合失效问题及数组偶数筛选实现需求
Solution: Filter Even Numbers with Arrow Function &
filter() Method Hey there, here's the exact implementation you need to get only even numbers from the numbers array using the built-in filter() method paired with an arrow function:
var numbers = "TBD"; var evens = () => { return numbers.filter(num => num % 2 === 0); };
Quick breakdown of how this works:
- The
filter()method iterates over every element in thenumbersarray, and returns a new array containing only elements that pass the test defined in the callback function. It won't modify the originalnumbersarray, which is perfect here. - The arrow function
num => num % 2 === 0is the test:num % 2calculates the remainder when the element is divided by 2- If the remainder is
0, the element is an even number, so it gets included in the resulting array
- We can even shorten the
evensarrow function further (since it's a single return statement) to make it more concise:
var evens = () => numbers.filter(num => num % 2 === 0);
This implementation will work perfectly even when the numbers variable is modified during testing—every time you call evens(), it will use the current state of the numbers array to generate the list of even numbers.
内容的提问来源于stack exchange,提问作者Kzeroone
相关产品推荐
相关产品推荐

