2016-04-29 79 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)和其他方法 –