javascript - 数组中所有值作为 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>
解决方案
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>
推荐阅读
- angular - I want to remove identity server from "ABP" angular app
- css - font-feature-settings : 'tnum' , 'lnum' : Not Working
- xpath - XPath text() returns 2 Values how to combine them to one
- java - Spring WebClient odd behaviour
- excel - 如何选择具有条件格式范围的活动单元格和活动单元格列
- sql - 如何有效计算多条经/纬度之间的最短距离(Oracle SQL)?
- excel - VBA 外部数据源
- mongodb - 匹配聚合管道中的任何日期元素 $
- git - 用于私有 gitlab 存储库的 Ansible-Galaxy,只为所有角色引用一个角色的文件
- excel - Excel - 自动递增值的公式/宏