我有一组随机数,想要计算每个数字出现在数组中的次数。
我有以下代码,但我无法弄清楚如何在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>
答案 0 :(得分:0)
使用以下代码
function f(){
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 (i=0;i<1000;i++){
if(arr[i]==1){
count1++;
}
if(arr[i]==2){
count2++;
}
if(arr[i]==3){
count3++;
}
if(arr[i]==4){
count4++;
}
if(arr[i]==5){
count5++;
}
}
document.getElementById("count1").innerHTML=count1;
document.getElementById("count2").innerHTML=count2;
document.getElementById("count3").innerHTML=count3;
document.getElementById("count4").innerHTML=count4;
document.getElementById("count5").innerHTML=count5;
}
答案 1 :(得分:0)
在分配随机数的同时,使用第二个数组计算频率会更好(更简单,更快捷),然后检查此数组并将值放入表格单元格中。此外,更容易通过class
识别表格单元格,而不是给它们所有类似的id
。 (jsfiddle)
var arr = [], counts = [],
countCells = document.getElementsByClassName('count');
function getRandom(num) {
return Math.round(Math.random() * num) + 1;
}
for (var i = 0; i < 1000; i++) {
var r = getRandom(30);
arr.push(r);
counts[r] = (counts[r] || 0) + 1;
}
for (var i = 0; i < countCells.length; i++) {
countCells[i].innerHTML = counts[i + 1] || 0;
}
答案 2 :(得分:0)
不是问题,但您可以简化流程并计算所有值:
var arr = [],
totals = [];
function getRandom(num) {
return Math.round(Math.random() * num) + 1;
}
for(var i=0; i<1000; i++) {
var val = getRandom(30),
count = totals[val] || 0;
arr.push(val);
totals[val] = ++count;
}