[英]Recursive function returning undefined value
我想從多級結構中獲取對象
我為它編寫了函數但是即使返回它不是從函數和返回值中出來的,它繼續下一次遞歸。 我知道它返回到以前調用的函數的值,因為它的作用域阻止它被覆蓋,這就是為什么返回未定義的值
var selectedObj = findObjectByUid( existingStructure, selectedUid);
function findObjectByUid( root, selectedUid ) {
if( root.uniqueId === selectedUid ) {
return root;
}
if( root.children && root.children.length > 0 ) {
for( var k in root.children ) {
if( root.children[ k ].uniqueId === selectedUid ) {
return root.children[ k ];
} else if( root.children.length ) {
return findObjectByUid( root.children[ k ], selectedUid );
}
}
}
}
這里我想回到我的初始調用函數,當它匹配uid。
實際上,無論找到的節點如何,您都會與第一個孩子一起返回。
您可以使用臨時變量並存儲子檢查的結果,如果不是,則返回此值。
順便說一句,您可以直接將數組的子進行遞歸。
function findObjectByUid(root, selectedUid) {
if (root.uniqueId === selectedUid) return root;
if (!root.children || !root.children.length) return;
for (let child of root.children) {
let temp = findObjectByUid(child, selectedUid);
if (temp) return temp;
}
}
var selectedObj = findObjectByUid(existingStructure, selectedUid);
在陣列上使用此方法有三個問題。 首先,如果這些屬性是可枚舉的,for ... in也會迭代對象的原型屬性。 例如:
Array.prototype.voice = "James Earl Jones";
var tMinus = [
"Two",
"One",
"Blast off!"
];
var countdown = "";
for (var step in tMinus) {
countdown += tMinus[step] + "\n";
}
console.log(countdown);
// => "Two
// One
// Blast Off!
// James Earl Jones
// "
這可以通過使用hasOwnProperty來排除原型屬性來解決。 例:
for (var step in tMinus) {
if (tMinus.hasOwnProperty(step)) {
countdown += tMinus[step] + "\n";
}
}
這是更正后的代碼。 您已經在內部調用中使用了return findObjectByUid
,代碼在完成循環之前就已經終止了。
function findObjectByUid( root, selectedUid ,foundArr) {
if( root.uniqueId === selectedUid ) {
foundArr.push(root);
return root;
}
else if( root.children && root.children.length > 0 ) {
for( var k in root.children ) {
findObjectByUid( root.children[k], selectedUid,foundArr );
if(root.children[k]=== selectedUid){break;}
}
}
return foundArr.length>0?foundArr[0]:null;
}
示例json和調用方法
var root = {uniqueId:1,children:[{uniqueId:10},{uniqueId:11,children:[{uniqueId:21,children:[]},{uniqueId:22,children:[]},{uniqueId:23,children:[{uniqueId:31,children:[]},{uniqueId:32,children:[]}]}]},{uniqueId:12,children:[]},{uniqueId:13,children:[]}]};
findObjectByUid(root,32,[]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.