如果用户输入 5 个数字,可以说4, 4, 7, 7, 4
...... 4 发生了 3 次(最多)次。所以输出应该是4
。
如何使用 JavaScript 做到这一点?非常感谢您的帮助。谢谢!
到目前为止,我已经尝试过了。行得通,但是太长了,找个短小简单的办法。
PS这不是我的作业!
var n = parseInt(prompt("How many numbers do you like to enter?", ""));
var num = new Array();
for (i = 1; i <= n; i++) {
num[i] = parseInt(prompt("Enter a number", ""));
document.write("Entered numbers are: " + num[i] + "<br/>");
}
var total = new Array();
for (i = 1; i <= n; i++) {
var count = 1;
for (j = i + 1; j <= n; j++) {
if (num[i] == num[j]) {
count++;
}
total[i] = count;
}
}
var most = 0;
for (i = 0; i < n; i++) {
if (most < total[i]) {
most = total[i];
}
var val = i;
}
document.write("<br/>" + num[val] + " is occurred " + most + " times");