简体   繁体   中英

Not able to understand recursive behaviour in nested javascript object

I am trying to understand how recursive work with a nested js object which may have same key name. For example in the below object the keys are same in nest. So when I am looping I am expecting obj[keys] will always go the first line(marked as //Line 1).

I am trying to understand how js will know consider which nest to loop if all the keys have same name. Not sure where I am going wrong in understanding

 var obj = { a: { // Line 1 a: { // Line 2 a: { // Line 3 sweptArea: 5 } } } } function loop(obj, keyName) { for (var keys in obj) { if (obj.hasOwnProperty(keys) && typeof obj[keys] === 'object') { if (obj[keys][keyName] !== undefined) { console.log(obj[keys][keyName]) } else { // In my understanding in all the iteration it will point to obj.a marked as line one loop(obj[keys], 'sweptArea') } } } } loop(obj, 'sweptArea') 

When you say obj[keys] is only looks for a key of that name on obj . That expression, by itself, does no recursion.

The value passed to the variable defined to the obj argument is different each time the function is called.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM