我想在javascript中编写递归函数,但无法正常工作。我有一个json数组对象数据,我想根据键找到某些东西,然后再根据搜索对象中的gotopage键找到它。在javascript中搜索json对象的递归函数
like:find orange - > gotopage - > orange_store - > find - > orange_store - > gotopage - > yellow_store - >找到如此相同的过程以递归方式进行。请您帮助我在哪里出错我的方法。
[
{
"id": 1,
"find": "orange",
"gotopage": "orange_store"
},
{
"id": 2,
"find": "orange_store",
"gotopage": "yellow_store"
},
{
"id": 3,
"find": "black_store",
"gotopage": "black_store"
},
{
"id": 4,
"find": "yellow_store",
"gotopage": "white_store"
},
{
"id": 5,
"find": "black_store",
"gotopage": "red_store"
}
]
function searchRec(search, myArray) {
for (var i = 0; i < myArray.length; i++) {
var res = [];
if (myArray[i].find == search) {
if (myArray[i] !== null) {
console.log(myArray[i]);
res = searchRec(myArray[i].gotopage, myArray);
if (res !== null) {
return res;
}
return myArray[i];
}
}
}
}
function findNode(arr) {
for (i = 0; i < arr.length; i++) {
searchRec(arr[i].find, arr);
break;
}
}
console.log(findNode(json));
输出第一次迭代,但不起作用每次迭代:
Object {id: 1, find: "orange", gotopage: "orange_store"}
Object {id: 2, find: "orange_store", gotopage: "yellow_store"}
为什么第三对象找不到:yellow_store? –
您正在检查从'searchRec'返回的null,但永远不会返回null。在JavaScript中,索引数组中的缺失元素将产生'undefined'而不是'null'。 – ivo