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

JavaScript中使用filter过滤对象数组时[0]的作用是什么?

对象数组filter操作后加[0]的作用
  • Array.filter()是JavaScript数组的原生方法,执行后会返回所有满足过滤条件的元素组成的新数组,哪怕只有1个符合条件的元素,也会被包裹在数组内返回。
  • 末尾加[0]是数组下标访问操作,作用是取出filter返回的结果数组里的第一个元素,直接得到目标对象,而非包裹对象的数组。

代码示例

// 示例对象数组
const goodsList = [
  { id: 101, name: '无线耳机', price: 299 },
  { id: 102, name: '充电宝', price: 89 },
  { id: 103, name: '手机壳', price: 29 }
]

// 仅用filter的返回值是数组
const filterResult = goodsList.filter(item => item.id === 102)
console.log(filterResult) // 输出:[{ id: 102, name: '充电宝', price: 89 }]

// 加[0]后直接拿到目标对象
const targetGoods = goodsList.filter(item => item.id === 102)[0]
console.log(targetGoods) // 输出:{ id: 102, name: '充电宝', price: 89 }

注意事项

  • 如果没有符合过滤条件的元素,filter会返回空数组[],此时访问[0]会得到undefined,不会抛出语法错误。
  • 如果需求只是查找第一个符合条件的元素,更推荐使用Array.find()方法,性能更优(filter会遍历整个数组,find找到第一个匹配项就会终止遍历),且不需要额外加[0],写法更简洁:
// 等效于上面加[0]的filter写法
const targetGoods = goodsList.find(item => item.id === 102)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 10:48:02