我有一个随机数数组,想计算每个数字出现在数组中的次数。
我有以下代码,但无法弄清楚如何在 html 表中分配计数值。
JavaScript:
<script>
var arr = [];
function getRandom(num) {
return Math.round(Math.random() * num) + 1;
}
for (var i = 0; i < 1000; i++) {
arr.push(getRandom(30));
}
var count1 = 0;
var count2 = 0;
var count3 = 0;
var count4 = 0;
var count5 = 0;
for (var i = 0; i < 1000; i++) {
if (arr[i] == 1) {
count1++;
}
}
for (var i = 0; i < 1000; i++) {
if (arr[i] == 2) {
count2++;
}
}
for (var i = 0; i < 1000; i++) {
if (arr[i] == 3) {
count3++;
}
}
for (var i = 0; i < 1000; i++) {
if (arr[i] == 4) {
count4++;
}
}
for (var i = 0; i < 1000; i++) {
if (arr[i] == 5) {
count5++;
}
}
}
</script>
HTML:
<table border="1">
<tr>
<td>Number</td>
<td>Frequency</td>
</tr>
<tr>
<td>1</td>
<td id="count1" </td>
</tr>
<tr>
<td>2</td>
<td id="count2"></td>
</tr>
<tr>
<td>3</td>
<td id="count3"></td>
</tr>
<tr>
<td>4</td>
<td id="count4"></td>
</tr>
<tr>
<td>5</td>
<td id="count5"></td>
</tr>
<tr>
</table>