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

JavaScript编写移除对象数组中红色食物的函数运行异常求解决

问题原因与修复方案

你代码存在两个核心问题导致没有生效:

  • Array.filter()是纯函数,不会修改原数组,只会返回过滤后的新数组,你的代码没有接收这个返回值,过滤操作没有产生实际作用
  • 函数最后返回的是全局的foods原数组,没有返回过滤后的结果
  • 额外优化:filter的回调可以直接返回布尔表达式,不需要冗余的if-else判断

推荐写法(无副作用,返回新数组)

这种写法不会改动原数组,是业务开发中更推荐的实现:

function removeRed(foods) {
    return foods.filter(item => item.color !== 'red');
}

// 调用测试
let foods = [{ name: 'Apple', color: 'red' }, { name: 'Egg', color: 'white' }];
let result = removeRed(foods);
console.log(result); // 输出:[{ name: 'Egg', color: 'white' }]

若需要直接修改原数组的实现

如果你的需求就是要改动传入的原数组,可以用倒序遍历加splice实现:

function removeRed(foods) {
    // 倒序遍历避免删除元素后索引偏移漏检
    for (let i = foods.length - 1; i >= 0; i--) {
        if (foods[i].color === 'red') {
            foods.splice(i, 1);
        }
    }
    return foods;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 02:45:02