0

I have a simple question

have a nested list using recursion I have to print all the nested array as well as the value of main array .

In-put

var list = ['a', ['a','b','c',['a','b','c']],'b', 'c'];
printList('foo',list); 

Out-put

foo.0.a
foo.1.0.a
foo.1.1.b
foo.1.2.c
foo.1.3.0.a
foo.1.3.1.b
foo.2.b
foo.3.c

But I am able to print only till one level deep

var list = ['a', ['a','b','c',['a','b','c']],'b', 'c'];
   var printList = function(name,list){

     for(var i=0;i< list.length;i++){

         if(Array.isArray(list[i]))
             {
               printList(name+'.'+i,list[i]);

             }
             else{

                 document.write(name+'.'+i+'.'+list[i]+'<br/>');
              
             }
              
     }
   }

   printList('foo',list);

I have added the code snippet have a look

Thanks

Vikram Anand Bhushan
  • 4,836
  • 15
  • 68
  • 130

1 Answers1

2

This is because the i in the for loop became a global variable, making it loose its value once in the recursion.

add var i; declaration before for loop in the function and the issue should be solved.

var list = ['a', ['a','b','c',['a','b','c']],'b', 'c'];
    var printList = function(name,list){
        var i;
        for(i=0;i< list.length;i++) {
            if(Array.isArray(list[i])) {
                printList(name+'.'+i,list[i]);
            } else {
                  document.write(name+'.'+i+'.'+list[i]+'<br/>');
            }
        }
    }

    printList('foo',list);
Arathi Sreekumar
  • 2,544
  • 1
  • 17
  • 28