2013-12-17 95 views
1

我写在道场的应用程序,并正尝试执行以下代码回路:的Javascript结束过早

/*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仅仅是使用JSON元素的数组。 for循环正确运行第一个元素,分别记录“渲染循环0”和“2”到控制台。但是,for循环然后结束而不执行第二次。

我运行了底部的两行代码,以确保它不是元素本身的问题,并且都正确执行。任何人有任何建议?

顺便说一句,我使用此代码重新启动元素从数据库中拉出后的渲染器。这是DojoX日历小部件的修改版本。

+0

硬,没有看到更多的代码来说,但我怀疑的是,这是一个范围界定问题。循环内的某个东西可能会设置'i'的值,这会导致您的循环提前保释。 – rossipedia

+0

你是对的!我将我改为k,并且一切都完美无缺!非常感谢你,我一直盯着这个2天,无法想象它! – Jay

回答

1

(将其移至评论的答案)。

很难说没有看到更多的代码,但我的怀疑是这是一个范围问题。循环内的某个东西可能会设置i的值,这会导致循环提前保释。

你需要确保你做的是声明函数中的变量将要使用它们。取而代之的是:

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); 
} 

这样做:

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); 
} 

你还需要确保被称为是使用可变i有它自己的声明为变量,循环中的任何代码。

有关JavaScript的作用域一个很好的答案,看this question