gpt4 book ai didi

javascript - 如何从递归函数中中断和返回?

转载 作者:数据小太阳 更新时间:2023-10-29 04:10:27 24 4
gpt4 key购买 nike

使用下面的代码,函数返回了几次。我需要打破递归并只返回一次结果。

知道如何解决吗?

http://jsfiddle.net/xhe6h8f0/

var data = {
item: [{
itemNested: [{
itemNested2: [{
id: "2"
}]
}]
}]
};

function findById (obj, id) {
var result;
for (var p in obj) {
if (obj.id) {
if(obj.id == id) {
result = obj;
break; // PROBLEM HERE dos not break
}
} else {
if (typeof obj[p] === 'object') {
findById(obj[p], id);
}
}
}
console.log(result);
return result;
}
var result = findById(data, "2");
alert(result);

最佳答案

如果找到匹配项,则需要返回该值。而在父调用中,如果递归调用返回一个值,那么它也必须返回那个值。你可以像这样修改你的代码

function findById(obj, id) {
var result;
for (var p in obj) {
/*
if `id` is not in `obj`, then `obj.id` will evaluate to
be `undefined`, which will not be equal to the `id`.
*/
if (obj.id === id) {
return obj;
} else {
if (typeof obj[p] === 'object') {
result = findById(obj[p], id);
if (result) {
return result;
}
}
}
}
return result;
}

现在,

var result = findById(data, "2");
console.log(result);

将打印

{ id: '2' }

关于javascript - 如何从递归函数中中断和返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27485691/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com