-2
for (i = 1; i < this.people.length; i++) {
        peoplePicks[i] = this.people[i].chooseAction(peopleChoices[i]);
    }

I have this for loop within my JavaScript program. It runs for ever, even though the length of the array that I am passing to it is 2. when I print the value of i after the statement of the for loop, I get 0. So it seems like i is being decremented by executing the for loop's statement. How can I fix this?

H.F.
  • 29
  • 2
  • 1
    What does that `chooseAction()` function look like? In the code you posted, there's no declaration for `i`. If that's the same case in that `chooseAction()` function, then that's your problem. – Pointy Dec 16 '18 at 19:59
  • 4
    What happens if you change the `for` loop so that it's `for (var i = 1; ...`? – Pointy Dec 16 '18 at 20:01
  • In the chooseAction() function, I use another for loop of the form for (i = 0; i < choices.length; i++) {}. Is that whats causing the problem? – H.F. Dec 16 '18 at 20:04
  • 2
    @H.F. Yes, it is. – Bergi Dec 16 '18 at 20:10
  • Adding var i = 1 does fix it. Thanks! Why is this? – H.F. Dec 16 '18 at 20:11
  • If you don't *declare* `i` with `var` or `let`, it will be assumed to be a **global** variable. Thus every function with a `for (i = 1; ...` loop will use the very same `i`. – Pointy Dec 16 '18 at 20:41

1 Answers1

1

Add var before your i variable in the initialising of your for loop.

Like this for (var i = 1; i < this.people.length; i++) {

Cjmarkham
  • 9,484
  • 5
  • 48
  • 81
Lloyd Nicholson
  • 474
  • 3
  • 12
  • Adding var i = 1 does fix it. Thanks! Why is this? – H.F. Dec 16 '18 at 20:11
  • 1
    @H.F. You need to set I as a variable as you would with any other variable you create. A for loop is something I have struggled with as well. Remember that the for loop sets a variable first and then changes and uses it however you wish after then discards it after the loop of finished looping. No problem. You’re welcome. – Lloyd Nicholson Dec 16 '18 at 20:14