繁体   English   中英

javascript多维数组循环

[英]javascript multidimensional array loop

我有一些jquery代码,我正在尝试重写为基本的javascript。

问题是我有这个多维数组,我不知道如何为此编写for循环?

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

您可以使用单个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
            });
        }
    } 
}

我们在JS中有Array.prototype.forEach方法。 你可以像使用它一样

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM