中断递归函数

Break recursive function

在此函数中,我试图在 JSON 字符串中查找特定项目。我可以找到该项目,但问题是一旦找到该项目,我想打破 forloop。

我正在使用递归函数,因为我正在寻找的项目可能在树的深处。

我试过 break、break with label 和我找到的其他几种解决方案。

据我了解,当我试图打破时我不在循环中,而是在地图内部。

data = '[{"id":"123","name":"Level 1 1","href":"#","list":[{"id":"1235235","name":"Level 2 1","href":"#","list":[{"id":"63463634","name":"Level 2 1","href":"#"}]}]},{"id":"79699676","name":"Level 2 1","href":"#"},{"id":"959656454","name":"Level 3 1","href":"#"},{"id":"46346346346123","name":"Level 4 1","href":"#"}]';

var iteration = 0;
const find = "1235235"

function func(data, find) {
    Object.keys(data).forEach((k) => {
        iteration++;

        if(data[k]['id'] === find) {
            console.log("found " + data[k]['id']);
            this.call();
            break iteration; 
        }

        if(data[k]['list'] !== undefined) {
            this.func(data[k]['list'], find);
        }
    });
}

提前致谢!

您可以在查找时使用 Array#some 和 return。

function func(data, find) {
    return Object.keys(data).some((k) => {      // return result of iteration
        iteration++;

        if (data[k].id === find) {
            console.log("found " + data[k]['id']);
            //this.call();
            return true;                        // return on direct found
        }

        if (Array.isArray(data[k].list)) {
            return func(data[k].list, find);    // return result of nested search
        }
    });
}

var data = [{ id: "123", name: "Level 1 1", href: "#", list: [{ id: "1235235", name: "Level 2 1", href: "#", list: [{ id: "63463634", name: "Level 2 1", href: "#" }] }] }, { id: "79699676", name: "Level 2 1", href: "#" }, { id: "959656454", name: "Level 3 1", href: "#" }, { id: "46346346346123", name: "Level 4 1", href: "#" }],
    iteration = 0,
    find = "1235235";

func(data, find);
console.log(iteration);

您还可以使用已经支持中断的 for .. of 循环:

var data = [{"id":"123","name":"Level 1 1","href":"#","list":[{"id":"1235235","name":"Level 2 1","href":"#","list":[{"id":"63463634","name":"Level 2 1","href":"#"}]}]},{"id":"79699676","name":"Level 2 1","href":"#"},{"id":"959656454","name":"Level 3 1","href":"#"},{"id":"46346346346123","name":"Level 4 1","href":"#"}];

var iteration = 0;
const find = "1235235"

function func(data, find) {
    for (const k of Object.keys(data)) {
        iteration++;

        if(data[k]['id'] === find) {
            console.log("found " + data[k]['id'] + " in iteration " + iteration);
            //this.call();
            break;
        }

        if(data[k]['list'] !== undefined) {
            return func(data[k]['list'], find);
        }
    };

    return false;
}

func(data, find);