1

I'm using the following for loop and as it is written below it alerts 0, 1, 2, 3, 4, 5, 6, 7, 8 (like it should) but when I uncomment set(buttons, i) it alerts 0, 2, 4, 6, 8.

for(i = 0; i < layerOrder.length; i++){
    alert(i);
    //set(buttons, i);
}

I'm very confused by this behavior because I have always assumed that integers were passed by value and not reference.

Is it possible to modify the for loop index variable in a function method like in my set() method? If so I can focus my time on debugging that.

spencer.sm
  • 19,173
  • 10
  • 77
  • 88
  • primitives are passed by value. what's the code of `set()`? does it use a variable `i`? have you declared it inside the function? – Thomas May 27 '16 at 20:47
  • The code that you've provided in your question won't reproduce the problem you're having. You probably ought to declare `i` in the `for` loop itself, rather than referencing a global variable `i`. – Robert Harvey May 27 '16 at 20:49
  • There's quite a bit of code involved to reproduce the problem. I followed it back to this for loop but I understand now it was a question of scope. Adding `var i = 0` did actually solve the problem. – spencer.sm May 27 '16 at 20:53

2 Answers2

3

This looks like something that is caused by leaving out the var. Please update your first line to read:

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

Please refer to this page for more info: "var" or no "var" in JavaScript's "for-in" loop?

Community
  • 1
  • 1
Kenny Grage
  • 1,124
  • 9
  • 16
1

You must be incrementing i in set method.

Since you have not described i as local variable by prefixing var keyword it is treated as a global variable in for loop. And hence is modified in set method. In javascript to declare a variable locally prefix it with var or else they are defined as global variables.

GMchris
  • 5,439
  • 4
  • 22
  • 40
Aditya
  • 861
  • 5
  • 8