2013-12-17 98 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