2012-10-13 56 views
0

嗨,大家好我有一小段代碼在jquery中,我有一個問題。看來,循環跳過第二個參數(當我= 2),你能告訴我什麼是錯的?JavaScript for循環「跳過價值」

這裏是代碼:

var items = $(".item").length; 
    var currentIndex = items; 

    place(currentIndex); 

    function place(index){ 
     var s1 = Math.floor(items/2); 

     for (i = 1; i <= items; i++){ 
      (function(i, index){ 

       if (i <= s1){ 
        var id = findNext(1, i); 
        console.log("i = " + i + " > id = " + id); 
       } else if (i > s1){ 
        console.log("i = " + i); 
       } 

      })(i, index); 
     } 
    } 

    function findNext(index, times){ 
     var result = index; 

     for (i = 1; i <= times; i++){ 
      if (result == items){ 
       result = 1; 
      } else { 
       result ++; 
      } 
     } 

     return result; 
    } 

控制檯輸出顯示了這個:

i = 1 > id = 2 
i = 3 
i = 4 

如此看來,對於循環躍過第二個參數(i = 2時),你能告訴我什麼是錯的?

回答

1

在你的主迴路功能place裏面,你定義一個全局變量i。你在findNext裏面做同樣的事情,從而覆蓋原來的i變量。使用var關鍵字定義i,因此只能在創建它的範圍內訪問它。

​​