2016-04-29 81 views
1

我有一些jquery代碼,我試圖重新寫入基本的JavaScript。javascript multidimensional數組循環

問題是我有這個多維數組,我不知道我將如何爲此編寫for循環?

$.each(wordcount, function(w, i) { 
     if (i > 1) { 
      constrain++; 
      if (constrain <= 2) { 
       topwords.push({ 
        'word': w, 
        'freq': i 
       }); 
      } 
     } 
    }); 
+1

你能提供一個數組中的值的例子嗎? – Jordumus

回答

2

你可以用一個單一的for循環做到這一點:

for (var i = 0; i < wordcount.length; i++) { 
    var w = wordcount[i]; 
    if (i > 1) { 
     constrain++; 
     if (constrain <= 2) { 
      topwords.push({ 
       'word': w, 
       'freq': i 
      }); 
     } 
    } 
} 
+0

哦,是的,我看到了 - 我可以使用.length :) –

+0

@AmyNeville這是遍歷或步行穿過陣列的傳統方式。 –

+0

@AmyNeville很高興能幫到 –

1

我們在JS Array.prototype.forEach方法。你可以使用它像

wordcount.forEach(function(w, i) { 
    if (i > 1) { 
     constrain++; 
     if (constrain <= 2) { 
      topwords.push({ 
       'word': w, 
       'freq': i 
      }); 
     } 
    } 
}); 
+0

有趣的是,它和JQuery一樣兼容嗎? –

+0

是的。即使這是更多的功能寫作風格和推薦的方式。 我建議你也查找['Array.prototype.map'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)和其他方法 –