2015-05-21 47 views
1

我想遍歷變量pieces,但不知何故它不會觸發。在下面的功能中,pieces.length轉4,但piecesNew[] - 而且console.log(i)永遠不會到達。無法進入我的循環(Javascript)

發生了什麼事?

self.reworkPieces = function(pieces) { 

     var piecesNew = []; 

     console.log(pieces.length) 

     for (var i; i <= pieces.length; i++) { 

      console.log(i) 

      piecesNew[i] = { 
       c: pieces[i].r, 
       r: pieces[i].c, 
       p: i 
      } 

     } 

     console.log(piecesNew) 

     return piecesNew; 

    }; 
+2

設置你的'i'至0 ... – MMM

+0

這裏'angularjs'標籤的需求是什麼? – Arulkumar

+0

刪除了angularjs標記 – JohnAndrews

回答

7

undefined小於任何數量。

var i; // undefined 
i < 10; // false 
i > 10; // false 

你只需要確保i等於0

您還希望i到永遠等於pieces.length所以使用<代替<=(陣列的最後一個索引始終length - 1,例如長度爲3的陣列具有索引0,1和2 - 第一個索引始終0,而不是1)

所以:

for (var i = 0; i < pieces.length; i++) { 
    ... 
+1

更準確地說,任何數字與undefined的比較都是錯誤的。 –

+0

@DanielCook:不正確,'undefined!= 0'是'true',如果你把它當作比較 – MMM

+0

謝謝,我明白了! – JohnAndrews

2
self.reworkPieces = function(pieces) { 

    var piecesNew = []; 

    console.log(pieces.length) 

    for (var i = 0; i <= pieces.length; i++) { 

     console.log(i) 

     piecesNew[i] = { 
      c: pieces[i].r, 
      r: pieces[i].c, 
      p: i 
     } 

    } 

    console.log(piecesNew) 

    return piecesNew; 

}; 
2

變化:

for (var i; i <= pieces.length; i++) 

要:

for (var i = 0; i < pieces.length; i++) 
3

變量定義值i,var i = 0

self.reworkPieces = function(pieces) { 

     var piecesNew = []; 

     console.log(pieces.length) 

     for (var i = 0; i <= pieces.length; i++) { 

      console.log(i) 

      piecesNew[i] = { 
       c: pieces[i].r, 
       r: pieces[i].c, 
       p: i 
      } 

     } 

     console.log(piecesNew) 

     return piecesNew; 

    }; 
1

初始化變種I = 0開始,然後它會工作

self.reworkPieces = function(pieces) { 

      var piecesNew = []; 

      console.log(pieces.length) 

      for (var i = 0; i <= pieces.length - 1; i++) { 

       console.log(i) 

       piecesNew[i] = { 
        c: pieces[i].r, 
        r: pieces[i].c, 
        p: i 
       } 

      } 

      console.log(piecesNew) 

      return piecesNew; 

     }; 
+0

this for(var i = 0; i <= pieces.length - 1; i ++)循環只迭代數組元素從零索引到最後一個索引 –