0

I'm trying to write a simple for loop inside of an object. Essentially what it is doing is setting the Z position of the object before it plus delta, with the exception that the 0th object simply adds delta to it's original position. Below is the code I am using to do this:

        this.objs[0].setZ(this.objs[0].getZ()+delta);
        var i;
        for (i = 0; i < this.n; i++) {
            this.objs[i+1].setZ(this.objs[i].getZ()+delta); 
            alert("i = " + i + " i+1 =" + i+1);
        } 

For some reason the alert returns i = 0 i+1 = 01 on the first pass and i = 1 i+1 = 11 on the second pass. This seems like it is treating i as a string or something, since I would expect the alert to print out i = 0 i+1 = 1 on the first pass and i = 1 i+1 = 2 on the second.

I think this seems to be confirmed by the following TypeError I get in when I run the code in Firefox Development Tools.

TypeError: this.objs[(i + 1)] is undefined

What exactly am I doing wrong here that i+1 is the wrong type?

----EDIT----

I noticed the for loop was going out of bounds so I changed it to this:

    for (i = 1; i < this.n; i++) {
        this.objs[i].setZ(this.objs[i-1].getZ()+delta); 
        alert(this.n);
    } 
}

(the value of this.n = 3). For some reason this keeps going through the loop when i=3. I have no idea why..

ryanmattscott
  • 321
  • 5
  • 17

1 Answers1

0

It's true that string concatenation is being used instead of addition, but that's not causing your error. On the last run through the loop, i is equal to n - 1, but you're trying to access element n, which doesn't exist. Change i < this.n to i < this.n - 1 in your for loop.

mooiamaduck
  • 2,066
  • 12
  • 13
  • Or iterate in reverse `for(var i = this.n; i > 0; i--)` which I find easier to read and can be faster; http://stackoverflow.com/questions/8689573 – Dave Anderson Aug 24 '15 at 03:21
  • @DaveAnderson I think you mean `for(var i = this.n - 1; i > 0; i--)`. Otherwise you get another off-by-one error. – mooiamaduck Aug 24 '15 at 04:01
  • @ryanmattscott What is the value of `this.n` that is printed? And why not use `this.objs.length`? – mooiamaduck Aug 24 '15 at 04:02
  • `this.n` and `this.objs.length` both are 3. I'll switch to `this.objs.length`, I didn't think of doing it that way. It's definitely better, I just tend to be professional at doing things the hard way. – ryanmattscott Aug 24 '15 at 04:08