递归搜索 - Javascript

问题描述 投票:0回答:0

我有以下递归函数用于在某些数组中搜索“键”字符串,这只是一个练习,但我很难理解为什么它没有完成在所有嵌套数组中的搜索

const middleBox1 = ['empty', 'empty'];
const middleBox2 = ['empty', 'empty'];
const middleBox3 = ['empty', 'key'];
const middleBox4 = [middleBox1, middleBox3];


const mainBox = [middleBox2, middleBox4];

function searchKey(arr) {
  for (i = 0; i <= arr.length; i++) {
    if (arr[i] == 'key') {
      return 'nice key bro'
    } else if (typeof arr[i] == 'object') {
      searchKey(arr[i])
    }
  }
  return
}

如果我调用

searchKey(mainBox);
,它会返回未定义,但是当使用
middleBox3
时,它会找到密钥。

我希望它能在嵌套框中找到钥匙。我很确定问题出在我的逻辑实现上。

javascript recursion search
© www.soinside.com 2019 - 2024. All rights reserved.