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

JavaScript中筛选Gender为0且Color为Red的数组对象求助

筛选数组中符合条件的记录:Gender为0且Color为Red

要从给定的student数组里找出目标记录,用filter()方法就可以完成——map()主要用来转换数组元素,不是做筛选的,别搞混了。

直接看代码实现:

let student = [
    {
        "ID": "1",
        "Name": "Senpai",
        "Gender": "1",
        "Class": "32",
        "Strength": "0",
        "Hairstyle": "1",
        "Color": "Black"
    },
    {
        "ID": "2",
        "Name": "Yui Rio",
        "Gender": "0",
        "Class": "11",
        "Strength": "0",
        "Hairstyle": "2",
        "Color": "Red"
    },
    {
        "ID": "3",
        "Name": "Yuna Hina",
        "Gender": "1",
        "Class": "12",
        "Strength": "0",
        "Hairstyle": "3",
        "Color": "Red"
    },
    {
        "ID": "4",
        "Name": "Koharu Hinata",
        "Gender": "0",
        "Class": "21",
        "Strength": "0",
        "Hairstyle": "4",
        "Color": "Green"
    },
    {
        "ID": "5",
        "Name": "Mei Mio",
        "Gender": "1",
        "Class": "22",
        "Strength": "0",
        "Hairstyle": "5",
        "Color": "Blue"
    }
];

// 筛选Gender为0且Color为Red的记录
const result = student.filter(item => {
  return item.Gender === "0" && item.Color === "Red";
});

console.log(result);

代码说明:

  • filter()会遍历数组中的每个元素,对每个元素执行回调函数
  • 回调函数里的item.Gender === "0" && item.Color === "Red"是判断条件,只有两个条件同时满足的元素,才会被保留到新数组result里
  • 运行后,result里只会包含ID为2的Yui Rio这条符合条件的记录

内容的提问来源于stack exchange,提问作者Neha Verma

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 23:20:26