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

JavaScript:查找指定对象在数组中的索引错误修复咨询

修复whereIsAlice函数的问题

看起来你的whereIsAlice函数大概率是犯了一个常见的小错误:初始化默认索引值时用了2,而不是表示“未找到匹配项”的标准值-1。当传入friends2时,因为数组里没有名为"Alice"的对象,函数就直接返回了这个错误的默认值,导致两次调用都输出2。

核心修复思路

  • 初始化默认索引为**-1**(这是JavaScript中约定俗成的“未找到”返回值)
  • 遍历数组时,仅在找到firstName严格等于"Alice"的对象时,更新索引为当前位置
  • 若遍历结束后无匹配项,保持默认的-1返回

具体实现方案

你可以选择两种方式实现,根据自己的需求来:

方案1:使用原生findIndex方法(最简洁高效)

JavaScript数组的findIndex方法天生就是干这个的——它会返回第一个匹配元素的索引,找不到则自动返回-1,完美适配你的需求:

function whereIsAlice(friendsArray) {
  return friendsArray.findIndex(friend => friend.firstName === "Alice");
}

方案2:手动遍历数组(适合理解底层逻辑)

如果你想手动实现遍历逻辑,一定要注意初始化索引为-1:

function whereIsAlice(friendsArray) {
  let aliceIndex = -1; // 初始化为未找到的状态
  for (let i = 0; i < friendsArray.length; i++) {
    // 严格匹配firstName为"Alice"
    if (friendsArray[i].firstName === "Alice") {
      aliceIndex = i;
      // 如果你只需要第一个匹配项,可以直接break跳出循环,提升性能
      break;
    }
  }
  return aliceIndex;
}

验证效果

  • 调用whereIsAlice(friends1):会定位到索引为2的Alice对象,返回2
  • 调用whereIsAlice(friends2):数组中无匹配项,返回-1

这样就能完全符合你的预期了!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:29:30