【问题标题】:javascript multidimensional array loopjavascript多维数组循环
【发布时间】:2016-04-29 10:15:44
【问题描述】:

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

问题是我有这个多维数组,但我不确定如何为此编写一个 for 循环?

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

【问题讨论】:

  • 你能提供一个数组中的值的例子吗?

标签: javascript jquery multidimensional-array


【解决方案1】:

你可以用一个 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
            });
        }
    } 
}

【讨论】:

  • 哦,是的,我明白了 - 我可以使用 .length :)
  • @AmyNeville 这是传统的遍历数组的方式。
  • @AmyNeville 很高兴为您提供帮助
【解决方案2】:

我们在 JS 中有Array.prototype.forEach 方法。你可以像

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

【讨论】:

  • 有意思,是不是和 JQuery 一样兼容?
  • 确实如此。甚至这更像是一种功能性的写作风格和推荐的方式。我建议你也寻找Array.prototype.map和其他方法
猜你喜欢
  • 1970-01-01
  • 2016-02-07
  • 1970-01-01
  • 1970-01-01
  • 2012-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-15
相关资源
最近更新 更多