javascript - js recursive function not returning correct child object -
i'm trying write recursive function returns correct nested object within model, based on array of indexes.
my console log labelled 'inside function' shows correct obj! baffling me after return obj, function appears run again , return parent.
var model = [ { name: 'item 1' }, { name: 'item 2', sub: [ { name: 'item 2.1' }, { name: 'item 2.2' }, { name: 'item 2.3' } ] }, { name: 'item 3' }, { name: 'item 4' } ]; function getobj(collection, array) { var data = collection[array[0]]; if(array.length > 1) { array.shift(); arguments.callee(data.sub, array); } console.log('inside function', data); return data; } var obj = getobj(model, [1, 2]); // expecting obj.name === 'item 2.3' console.log('result', obj); // obj.name === 'item 2'
when you're recursing
arguments.callee(data.sub, array);
you're not returning result, instead you're ignoring result , returning data initial call.
try adding return
line result of recursive call result of overall function.
also aware arguments.callee
won't work in strict mode.
warning: 5th edition of ecmascript (es5) forbids use of arguments.callee() in strict mode. avoid using
arguments.callee()
either giving function expressions name or use function declaration function must call itself.
to work in strict mode, do
return getobj(data.sub, array);
Comments
Post a Comment