数组中所有值作为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>

在每次迭代中,您都会覆盖元素的文本,因此只显示最终文本。您应该将文本存储在一个变量中,并使用该变量:

$(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>

最新更新