我想在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