Reputation: 2111
this.draw = function() {
console.log(this.buttonList.length);
for(a = 0; a < this.buttonList.length; a++) {
console.log(this.buttonList.length, a);
this.buttonList[a].draw();
}
};
So I have this function within an object, and it's not working the way I expected it to. When I run it with the above console.log
statements, it logs this on the console:
2
2 0
This seems to tell me that my for loop is not looping through every item on the array, and I've been scratching my head over why that would be for a quite a while now. Does anyone know why it's only performing the action for a = 0?
edit: I don't know if this makes a difference, but this function is called about 60 times every second.
Upvotes: 0
Views: 1472
Reputation: 24385
There are atleast three possibilities for the behavior:
a
is overwritten (as per dystroys
answer).buttonList
don't have a draw
function.this
in the function definition of draw
is an element in the buttonList
.The first two possibilities are easy to fix but the third one depends on what your intentions are, i.e. what do you wish to accomplish. To fix it we need more information.
Any one of the three possibilities (or combinations of the possibilities) could account for the behavior.
The first possibility is explained by dystroy
.
The second possibility will stop excecution if an element doesn't have a draw
function. In this case it seems to be the first element.
The third possibility will render in a stack overflow due to infinite recursion. The draw
function is called over and over again just logging to console 2
then 2 0
until all the stack is consumed at which point the execution stops.
Upvotes: 0
Reputation: 382112
Adding var
would probably fix it :
this.draw = function() {
console.log(this.buttonList.length);
for(var a = 0; a < this.buttonList.length; a++) {
console.log(this.buttonList.length, a);
this.buttonList[a].draw();
}
};
There's very probably another point of your code where you change a
. You should be careful with the variable declarations.
Upvotes: 6