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

箭头函数与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 the numbers array, and returns a new array containing only elements that pass the test defined in the callback function. It won't modify the original numbers array, which is perfect here.
  • The arrow function num => num % 2 === 0 is the test:
    • num % 2 calculates 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 evens arrow 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:34:19