var moreThanHalfNum = function (arr) {
if(arr.length==0)
return '数组为空';
var result = arr[0];
var times = 1;
var length = arr.length;
for (var i = 0; i < length; i++) {
if (times == 0) {
result = arr[i];
times = 1;
}else if(result == arr[i]){
times++;
}else{
times--;
}
}
return result;
};
var arr = [1, 2, 3, 2, 2, 2, 5, 4, 2];
console.log(moreThanHalfNum(arr));
控制台输出
2