【问题标题】:How to write a recursive function that searches through an array to find the index of a target element (JS)如何编写递归函数来搜索数组以查找目标元素的索引(JS)
【发布时间】:2023-01-07 08:49:14
【问题描述】:

这是我当前的函数——我理解使用递归的前提,但似乎无法获得下面的函数来返回元素的索引——当前返回未定义。

我的目标是创建此函数的递归版本(使用 for 循环:

// function searchIndex(arr, target) {
//     for(let i = 0; i < arr.length; i++) {
//         if(arr[i] == target) {
//             return arr.indexOf(target);
//         }
//     }
//     return -1;
// }

我目前的代码如下:

function searchRecursive(arr, target) {
    // base case
    if (arr[0] === target) {
        return 0;
    }
    else {
        searchRecursive(arr.slice(1), target)
    }
}

【问题讨论】:

  • else 缺少返回
  • 考虑不使用 else,因为您要提早返回。
  • 这将始终返回 0 或超过 max.callstack

标签: javascript recursion


【解决方案1】:

在这里,您以递归方式具有相同的功能:

function searchIndex(arr, target) {
  if (arr.length === 0) {
    return -1;
  }
  if (arr[0] === target) {
    return 0;
  }
  const index = searchIndex(arr.slice(1), target);
  if (index === -1) {
    return -1;
  }
  return index + 1;
}

【讨论】:

    猜你喜欢
    • 2019-06-08
    • 1970-01-01
    • 2019-10-02
    • 1970-01-01
    • 1970-01-01
    • 2021-05-10
    • 2010-11-07
    • 1970-01-01
    • 2016-11-13
    相关资源
    最近更新 更多