javascript - can't make this (simple) recursive function return a value -
javascript - can't make this (simple) recursive function return a value -
i got next function write in mill can utilize afterward:
treeview.factory('utils', function () { return{ // util finding object 'id' property among array findbyid:function findbyid(a, targetid) { var indexresult = 0; (var = 0; < a.length; i++) { //console.log(targetid + " - " +a[i].id); if (a[i].id === targetid) { indexresult = i+1; console.log(a[indexresult-1]); break; } else { if(a[i].nodes instanceof array) { homecoming findbyid(a[i].nodes, targetid); } } } if(indexresult == 0) { } else { homecoming a[indexresult-1]; } } }; });
then in controller phone call that:
$scope.elementtoedit = utils.findbyid($scope.data,$stateparams.elementid); console.log($scope.elementtoedit)
and console logs "found" homecoming "undefined"!
do phone call mill wrong way ? doesn't seem because wrote outside angular , it's same. or late , can't see obvious ?
edit: issue has nil angular. info set isn't simple array array of array, each array containing children. believe function doesn't work because when functions finds right elements continues run on other array of same depth. trick global variable. isn't way ?
find fiddle here http://jsfiddle.net/morgorth/7njyuzxc/
final edit: error in js when recursive function have phone call homecoming this: homecoming findbyid(a[i].nodes, targetid);
you can't utilize return
in loop. utilize break
exit loop , homecoming after that
var ii = 0; (var = 0; < a.length; i++) { //console.log(targetid + " - " +a[i].id); if (a[i].id === targetid) { console.log("found"); ii = + 1; break; } else { if (a[i].nodes instanceof array) { findbyid(a[i].nodes, targetid); } } } if(ii == 0) homecoming 1; else homecoming a[ii - 1];
javascript angularjs
Comments
Post a Comment