在JavaScript中计算字符串中数字的出现次数
对于我上面的函数,它能够计算唯一字符的数量。例如,对于在JavaScript中计算字符串中数字的出现次数,javascript,jquery,Javascript,Jquery,对于我上面的函数,它能够计算唯一字符的数量。例如,对于1113,结果将是2,因为只有1和3。对于1134,结果将是3,因为有1、3和4 但我想举例来说,1133和1113,有相同的2个唯一的数字,即1和3。如何计算1和3的最大出现次数?对于1133它将是2,而对于1113它将是3,因为1出现了3次 我只需要计算字符串中出现次数最多的数字(仅限数字)。存储计数并找到计数的最大值。以下是放入函数的代码: $.each(string.split(''), function(){ if(!che
1113
,结果将是2,因为只有1和3。对于1134
,结果将是3,因为有1、3和4
但我想举例来说,1133和1113,有相同的2个唯一的数字,即1和3。如何计算1和3的最大出现次数?对于1133
它将是2,而对于1113
它将是3,因为1
出现了3次
我只需要计算字符串中出现次数最多的数字(仅限数字)。存储计数并找到计数的最大值。以下是放入函数的代码:
$.each(string.split(''), function(){
if(!check[this]){
count++;
check[this]=true;
}
})
您需要几个助手:
function getMostOccurrence(str) {
var check = {};
var maxOccurrences = 0;
// This part you already have...kind of
str.split('').forEach(function(num) {
// Set it the first time
if (typeof check[num] === 'undefined') {
check[num] = 0;
}
// Increase it
check[num] += 1;
});
// Find the max of that
for (var num in check) {
if (check.hasOwnProperty(num)) {
if (check[num] > maxOccurrences) {
maxOccurrences = check[num];
}
}
}
return maxOccurrences;
}
你的方法看起来更复杂。你介意评论/解释一下吗,这样我们就可以不用手动解码就能了解这里发生了什么?非常好。虽然我想知道您是否有任何理由使用
Array.prototype.reduce
作为迭代器?因为我不喜欢for
循环,它们既麻烦又难看。
// Given an object, it returns the values in an array
// {a:1, b:2} => [1,2]
var values = function(x) {
return Object.keys(x).map(function(k){return x[k]})
}
// Given an array, it counts occurrences
// by using an object lookup.
// It will return an object where each key is an array item
// and each value is the number of occurrences
// [1,1,1,3] => {'1':3, '3':1}
var occurrences = function(xs) {
return xs.reduce(function(acc, x) {
// If key exists, then increment, otherwise initialize to 1
acc[x] = ++acc[x] || 1
return acc
},{})
}
// Composing both helpers
var maxNumberOccurrence = function(n) {
// To get the maximum value of occurrences
// we use Math.max with `apply` to call the function
// with an array of arguments
return Math.max.apply(0, values(occurrences(n.toString().split(''))))
}
maxNumberOccurrence(1113) //=> 3