javascript - 如何编写递归来定位多维数组中的值

标签 javascript

我正在尝试编写一个递归函数来定位多维数组中的值。这是我到目前为止所尝试过的:

var locate = function (arr,value) {
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] === value) {
            return true;
        } else if (Array.isArray(arr[i])) {
            locate(arr[i], value);
        }
    }
    return false;
}

但是,它不起作用:

console.log(locate(['a','b',['c','d',['e']]],'e'))
// => returns `false`, but should return `true`

我应该如何解决这个问题?

最佳答案

这是一个递归 DFS:

var locate = function (arr, value) {
    // start at the current array; we want to check every value
    for (var i = 0; i < arr.length; i++) {
        // if we've found our value, return immediately
        if (arr[i] === value) {
            return true;
        // if the element is an array, call locate on the element
        // and possibly return true
        // we don't want to return locate(arr[i], value) because
        // it could be found later on
        } else if (Array.isArray(arr[i]) && locate(arr[i], value)) {
            return true;
        } 
    }
    // reached the end of the current array, so return `false`
    // note, since we use `else if (... locate(arr[i], value)),
    // we won't stop the recursion before checking every possible value
    return false;
}

关于javascript - 如何编写递归来定位多维数组中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29691435/

相关文章:

javascript - 将生成的 JSON 写入文件 BabyParse

javascript - AngularJS ng-repeat 过滤功能未正确过滤

javascript - 如何使 React Portal 与 React Hook 配合使用?

javascript - 如何在导出中包含导入的模块?

javascript - 如何在常规 HTML、CSS 中绘制线条(如谷歌地图)

javascript - 将页面上的一堆输入存储到 JavaScript 数组中?

用于 Canvas html5 的 Javascript getImageData

javascript - Jquery : Can't find the bug, 可能有ID?

javascript - jQuery - append() 方法因空格而无法正常工作

javascript - 在聊天容器上 react 自动滚动到底部