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

5
  • 1
    So how should the desired output look like? Commented Jul 29, 2016 at 10:16
  • Possible duplicate of Access / process (nested) objects, arrays or JSON Commented Jul 29, 2016 at 10:21
  • @VisioN its not printing all the element of the array , If you see it is printing only till the end of the first array that is foo.1.x.vlaues it did not print foo.2.0.b and foo.3.0.c Commented Jul 29, 2016 at 10:22
  • @Teemu I am beginner in js do not understand how that question is related with my question Commented Jul 29, 2016 at 10:33
  • 1
    Undeclared variables assignment binds it to the global scope,typical JS Commented Jul 29, 2016 at 10:37

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.