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

如何使用filter方法移除数组对象(禁用箭头语法)并遍历更新后的数组

解决方法:用filter移除数组对象并遍历(非箭头函数版)

首先先修正你提供的数组语法错误(原代码缺逗号、字符串未加引号,会导致运行报错):

const array = [
  {
    name: 'JB',
    age: 28,
    dob: '12-17-1996'
  },
  {
    name: 'Jamey',
    age: 57,
    dob: '9-13-1965'
  },
  {
    name: 'Jayla',
    age: 30,
    dob: '11-18-1992'
  }
];

1. 用filter方法移除指定对象(非箭头函数)

filter 方法会创建一个新数组,包含所有通过测试的元素。我们用普通函数作为回调,返回保留元素的条件:

// 示例:移除name为'JB'的对象
const filteredArray = array.filter(function(item) {
  // 返回true的元素会被保留,false则被排除
  return item.name !== 'JB';
});

2. 遍历更新后的数组

可以用forEach(同样用普通函数)或者for循环遍历:

用forEach遍历

filteredArray.forEach(function(item) {
  console.log(`姓名:${item.name},年龄:${item.age},生日:${item.dob}`);
});

用for循环遍历(解决你返回undefined的问题)

你之前用for循环返回undefined,大概率是没正确收集符合条件的元素,或者错误地在循环内return。正确写法是先创建新数组收集结果,再遍历:

// 第一步:手动过滤数组
const newArray = [];
for (let i = 0; i < array.length; i++) {
  const currentItem = array[i];
  if (currentItem.name !== 'JB') { // 过滤条件
    newArray.push(currentItem);
  }
}

// 第二步:遍历过滤后的数组
for (let i = 0; i < newArray.length; i++) {
  console.log(newArray[i]);
}

注意:不要直接在循环里return(除非是函数内的逻辑),否则会提前终止循环且没有返回正确的数组。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 06:00:47