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

如何从含firstName和age的用户列表中筛选出同年龄用户?

筛选指定年龄的用户

实现方案

  • 定义一个接收目标年龄的函数,利用数组filter方法动态匹配用户年龄
  • 函数可灵活适配任意传入的年龄值,无需固定筛选条件

代码示例

const users = [
    {firstName: 'Rohan', age: 26},
    {firstName: 'Ronny', age: 22},
    {firstName: 'Ronnie', age: 23},
    {firstName: 'RohanB', age: 26},
];

// 筛选指定年龄的用户
function filterUsersByAge(targetAge) {
    return users.filter(user => user.age === targetAge);
}

// 动态传入年龄使用示例
const targetAge = 26; // 这里可以替换为任意动态传入的年龄值
const matchedUsers = filterUsersByAge(targetAge);
console.log(matchedUsers);
// 输出结果: [{firstName: 'Rohan', age: 26}, {firstName: 'RohanB', age: 26}]

可选优化:参数校验

如果需要处理非数字类型的传入参数,可在函数内添加校验逻辑:

function filterUsersByAge(targetAge) {
    // 仅处理数字类型的年龄参数
    if (typeof targetAge !== 'number') {
        return [];
    }
    return users.filter(user => user.age === targetAge);
}

内容的提问来源于stack exchange,提问作者Rohan Bisht

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 09:45:36