方法一:采用一个数字来储存每个数字出现的次数
let a = [1,2,3,3,2,2,3]
let countArr = []; //定义个数组来储存每个数字出现的次数,数组下标是对应的数字
for(let j=0; j<a.length; j++){
// 判断是否第一次出现
if(j === a.indexOf(a[j])){
countArr[a[j]] = 1
}else{
countArr[a[j]] = countArr[a[j]] + 1
}
}
let maxNum = 0 //储存数字的最多次数
for(let i=0; i<countArr.length; i++){
if(countArr[i] !== undefined && countArr[i] > maxNum){
maxNum = countArr[i]
}
}
for(let j=0; j<countArr.length; j++){
if(maxNum === countArr[j]){
console.log('出现最多的数字为:',j);
}
}
方法二:采用一个对象来存储,键表示该数字,值表示给数字出现次数
let a = [1,2,3,3,2,2,3,12,33,12,12,33]
let obj = {} //采用键值对来存储,键表示该数字,值表示给数字出现次数
let maxNum = 0
a.forEach((item,index) => {
if(a.indexOf(item) == index){
obj[item] = 1
}else{
obj[item] = obj[item] + 1
}
})
//找出谁是最大值
for(let i in obj){
if(obj[i] > maxNum){
maxNum = obj[i]
}
}
//根据最大值输出对应的数字
for(let j in obj){
if(obj[j] === maxNum){
console.log('出现次数最多的数字为',j,' ,次数为',obj[j]);
}
}