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

如何获取对象数组中指定属性值对应元素的索引?

查找数组中指定id对象的索引

你可以使用数组的findIndex()方法来实现,它的用法和你已经掌握的find()非常相似,区别在于findIndex()返回的是第一个符合条件的元素在数组中的索引,若找不到匹配元素则返回-1。

代码示例

const aaa = [
  {id: 10, val: "xx"},
  {id: 27, val: "tr"},
  {id: 13, val: "ut"}
];

// 查找id为27的对象的索引
const targetIndex = aaa.findIndex(obj => obj.id === 27);
console.log(targetIndex); // 输出:1

兼容旧环境的方案

如果需要兼容不支持findIndex()的旧环境(比如IE),可以用普通循环遍历:

const aaa = [
  {id: 10, val: "xx"},
  {id: 27, val: "tr"},
  {id: 13, val: "ut"}
];

let targetIndex = -1;
for (let i = 0; i < aaa.length; i++) {
  if (aaa[i].id === 27) {
    targetIndex = i;
    break; // 找到后立即跳出循环,提升效率
  }
}
console.log(targetIndex); // 输出:1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 01:02:05