使用For循环在数组中递归搜索 [英] Recursively Search in Array with a For Loop

查看:101
本文介绍了使用For循环在数组中递归搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有更好的搜索数组的方法,但是我真的很想了解在递归调用中找到值时如何返回.找到时记录日志不是问题,但发现时似乎无法使此返回为真.

I know there are better ways to search an array, but I really want to understand how to return when the value is found in a recursive call. Logging when found isn't a problem, but I can't seem to make this return true when found.

问题是基本的.使用for循环和递归,在多维数组中完全搜索一个值,如果找到则返回true,否则返回false.我尝试过返回递归函数以及我能想到的所有其他功能,但是没有什么能完全起作用的.

The problem is basic. Fully search multi-dimensional array for a value and return true if found or false if not found, using a for loop and recursion. I've tried returning the recursive function and everything else I can think of, but nothing works fully.

function lookForKey( arr ){
    for ( let i = 0; i < arr.length; i++ ) {
        if( arr[i] == "key" ){
            console.log( "Key found.");
            return true;
        } else if( Array.isArray( arr[i] ) ){
            lookForKey( arr[i] );
        }
    }

    return false;
}

let arr = [
    ["foo", "bar"],
    ["foo", "bar", "key"]
];

console.log( lookForKey( arr ) );

我对此表示感谢!

推荐答案

function lookForKey( arr ){
    for ( let i = 0; i < arr.length; i++ ) {
        if( arr[i] == "key" ){
            console.log( "Key found.");
            return true;
        } else if( Array.isArray( arr[i] ) ){
            if (lookForKey(arr[i])) return true;
        }
    }

    return false;
}

let arr = [
    ["foo", "bar"],
    ["foo", "bar", "key"]
];

console.log( lookForKey( arr ) );

有两个变化.首先,您必须在递归调用上获得回报.但是,如果递归调用返回false,则您不希望立即从调用方返回.您要继续循环.因此,您可以将其设置为条件条件,并且仅在递归调用返回true时才返回true.

So two changes. First, you have to have the return on the recursive call. However, if the recursive call returns false, you don't want to return immediately from the caller. You want to continue the loop. So you can make that a conditional and only return true if the recursive call returns true.

这篇关于使用For循环在数组中递归搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆