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

JavaScript函数无法定位数组首位拼写错误水果元素的问题求助

问题:找出拼写错误的水果索引

需求说明

  • 编写函数接收水果数组orchard,数组中仅有一个拼写错误的水果,函数需返回该错误水果的索引
  • 示例输入:['graep', 'grape', 'grape', 'grape'],预期返回0

我编写的代码

function findWrongWayFruit(orchard) {
  if (orchard.length < 3) {
    return 0;
  }

  const firstFruit = orchard[0];
  for (let i = 1; i < orchard.length; i++) {
    if (firstFruit !== orchard[i]) {
      return i;
    }
  }
  return 0;
}

console.log(findWrongWayFruit(['graep', 'grape', 'grape', 'grape']));

遇到的错误

运行代码时,测试用例「错误水果位于首位时应返回正确索引」失败,报错:

AssertionError: expected 1 to equal +0

问题分析

当前逻辑存在明显漏洞:默认把第一个元素当作「正确水果」,遍历后续元素时,只要发现不一样的就直接返回该元素的索引。但如果第一个元素本身就是错误的(比如示例中的情况),代码会把第一个正确元素的索引(示例里的1)返回,而不是错误元素的索引0。

修正后的代码

要解决这个问题,首先得确定正确的水果是什么——因为数组里只有一个错误,前三个元素中至少有两个是正确的,可通过前三个元素判断出正确值,再遍历数组找错误项:

function findWrongWayFruit(orchard) {
  if (orchard.length < 3) return 0;

  // 确定正确的水果类型
  let correctFruit;
  if (orchard[0] === orchard[1]) {
    correctFruit = orchard[0];
  } else if (orchard[0] === orchard[2]) {
    correctFruit = orchard[0];
  } else {
    // 前两个不一样,且第一个和第三个也不一样,说明第一个是错的,正确值为第二个
    correctFruit = orchard[1];
  }

  // 遍历数组找到错误项的索引
  for (let i = 0; i < orchard.length; i++) {
    if (orchard[i] !== correctFruit) {
      return i;
    }
  }
  return 0;
}

console.log(findWrongWayFruit(['graep', 'grape', 'grape', 'grape'])); // 输出 0

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 16:10:03