我正在dojo中编写一个应用程序,我正在尝试执行以下代码:
/*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循环正确地遍历第一个元素,分别将“render loop 0”和“2”记录到控制台。然而,for循环然后结束而不执行第二次。
我运行了底部两行代码,以确保它不是元素本身的问题,并且都正确执行。有人有什么建议吗?
顺便说一下,在从数据库中提取元素后,我正在使用此代码重新生成渲染器。这是DojoX日历小部件的修改版本。
答案 0 :(得分: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