Jay
Jay

Reputation: 47

Javascript for loop ending prematurely

I am writing an application in dojo, and am trying to execute the following code:

/*for (i = 0; i < mainProperties.calendar.store.data.length; i++) {
    console.log("render loop " + i);
    mainProperties.calendar.store.put(mainProperties.calendar.store.data[i]);
    console.log(mainProperties.calendar.store.data.length);
}*/

mainProperties.calendar.store.put(mainProperties.calendar.store.data[0]);
mainProperties.calendar.store.put(mainProperties.calendar.store.data[1]);

mainProperties.calendar.store.data is simply an array with json elements. The for loop correctly runs through the first element, logging "render loop 0" and "2", respectively, to the console. However, the for loop then ends without executing a second time.

I ran the bottom two lines of code to make sure it wasn't an issue with the elements themselves, and both execute correctly. Anyone have any suggestions?

Btw, I am using this code to re-fire renderers after the elements are pulled from a database. This is a modified version of the DojoX calendar widget.

Upvotes: 1

Views: 362

Answers (1)

rossipedia
rossipedia

Reputation: 59367

(moved this to an answer from a comment).

Hard to say without seeing more code, but my suspicion is that it's a scoping issue. Something inside the loop is probably setting the value of i, which is causing your loop to bail early.

What you need to make sure you do is declare the variables in the functions that are going to use them. Instead of this:

for (i = 0; i < mainProperties.calendar.store.data.length; i++) {
    console.log("render loop " + i);
    mainProperties.calendar.store.put(mainProperties.calendar.store.data[i]);
    console.log(mainProperties.calendar.store.data.length);
}

Do this:

var i; // <- declare here
for (i = 0; i < mainProperties.calendar.store.data.length; i++) {
    console.log("render loop " + i);
    mainProperties.calendar.store.put(mainProperties.calendar.store.data[i]);
    console.log(mainProperties.calendar.store.data.length);
}

You also need to make sure that any code that is called inside that loop that uses a variable i has it's own declaration for that variable.

For a good answer about javascript scoping, see this question

Upvotes: 1

Related Questions