You need to enable JavaScript to run this app. JavaScript过滤对象数组时报Cannot read property 'section' of undefined如何解决
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript过滤对象数组时报Cannot read property 'section' of undefined如何解决

问题原因

你调用filter方法时传入的回调函数参数逻辑错误:

  • Array.prototype.filter的回调函数第一个入参是当前正在遍历的数组成员本身,你这里orchestra.instruments数组的每个成员都是直接持有name、section属性的乐器对象
  • 你在判断逻辑中额外加了一层不存在的instruments属性,执行orchestraInstruments.instruments.section时,orchestraInstruments.instruments本身就是undefined,读取section自然会抛出类型错误。
修正方案

只需要修改过滤函数的判断逻辑即可,修正后的完整代码如下:

var orchestra = {};
orchestra.name = "Shawn";
orchestra.instruments = [
    {
        "name": "Guitar",
        "section": "String"
    },
    {
        "name": "Violin",
        "section": "String"
    },
    {
        "name": "Bass",
        "section": "String"
    },
    {
        "name": "Flute",
        "section": "Woodwind"
    },
    {
        "name": "Drums",
        "section": "Percussion"
    }
];
orchestra.director = "Wolfgang Mozart";

// 过滤逻辑可以直接简化为箭头函数写法,也可以保留原有函数写法修改判断逻辑即可
var stringInstruments = orchestra.instruments.filter(item => item.section === "String");

console.log(stringInstruments);

运行后控制台会正确输出所有属于String分组的乐器对象数组。

内容的提问来源于stack exchange,提问作者Shawn Fetanat

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 06:54:03