1

This is my script running on Google Chrome Version 58.0.3029.81 (64-bit) (Windows 10 x64)

<script>  
var givenArray = [23, 6, [2, [6, 2, 1, 2], 2], 5, 2];
var printArray = function (start, array) {
    for (i = 0; i < array.length; i++) {
        if (Array.isArray(array[i])) {
            printArray(start + 1, array[i]);
        }
        else {
            for (j = 0; j < start; j++) {
                document.write("&nbsp;&nbsp;&nbsp;&nbsp;");
            }
            document.write(array[i] + '<br/>');
        }
    }
};
printArray(0, givenArray);
</script>

This script should print

23
6
    2
        6
        2
        1
        2
    2
5
2

But it is printing only

23
6
    2
        6
        2
        1
        2

I mean, after the recursive call outer for loop ends or function returns.
What is the problem with this ?

Chitholian
  • 350
  • 1
  • 5
  • 14
  • 1
    http://stackoverflow.com/q/802854/815386 https://blog.dareboost.com/en/2016/09/avoid-using-document-write-scripts-injection/ https://developers.google.com/web/updates/2016/08/removing-document-write – zb' Apr 30 '17 at 10:27

1 Answers1

4

You're using gloabal i and j that are shared by all the printArray calls. Use var to make i and j local:

var printArray = function (start, array) {
    for (var i = 0; i < array.length; i++) {
//       ^^^^ here
        if (Array.isArray(array[i])) {
            printArray(start + 1, array[i]);
        }
        else {
            for (var j = 0; j < start; j++) {
//               ^^^^ and here
                document.write("&nbsp;&nbsp;&nbsp;&nbsp;");
            }
            document.write(array[i] + '<br/>');
        }
    }
};

Never use variables without declaration, unless you want them to be globals.

ibrahim mahrir
  • 28,583
  • 5
  • 34
  • 61