首页 > 解决方案 > 数组中所有值作为 div 的文本出现的次数

问题描述

这个问题中接受的答案非常优雅地将给定数组中所有值的出现次数记录到控制台。当我尝试将其设置为输入值或 div 的文本时,它只给出数组的最后一个值。

我想不通。原谅我的菜鸟。

$(document).on('click', 'button', function() {
  class Counter extends Map {
    constructor(iter, key = null) {
      super();
      this.key = key || (x => x);
      for (let x of iter) {
        this.add(x);
      }
    }

    add(x) {
      x = this.key(x);
      this.set(x, (this.get(x) || 0) + 1);
    }
  }

  results = new Counter(["john", "mark", "George", "mark", "john", "George", "john", "George", "bill"]);
  for (let [number, times] of results.entries())
    $("div").text(times + "x " + number)
});
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<button>LOG</button>
<div></div>

标签: javascriptjquery

解决方案


In each iteration you are overriding the element's text, as a result only the final text is shown. You should store the text in a variable and use that:

$(document).on('click', 'button', function () {

  class Counter extends Map {
      constructor(iter, key=null) {
          super();
          this.key = key || (x => x);
          for (let x of iter) {
              this.add(x);
          }
      }
      add(x) {
        x = this.key(x);
        this.set(x, (this.get(x) || 0) + 1);
      }
  }

  var res = "";
  results = new Counter(["john", "mark", "George", "mark", "john", "George", "john", "George", "bill"]);
  for (let [number, times] of results.entries()){
    res += times + "x " + number;
  }
  $("div").text(res);
  
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>LOG</button>
<div></div>


推荐阅读