js 获取字符串中出现次数最多的字符及其出现的次数

方法一

function getMaxChar1(str) {
  const obj = {};
  for (let i = 0; i < str.length; i++) {
    let c = str.charAt(i);
    if(obj[c])
      obj[c]++;
    else
      obj[c] = 1;
  }
  console.log('obj:', obj);
  let max = 1, char = '';
  Object.keys(obj).map(k => {
    if(obj[k] > max) {
      max = obj[k];
      char = k;
    }
  });
  console.log('max:', max, ';char:', char);
}

方法二

function getMaxChar2(str) {
  const b = str.split(''); // 将字符串拆成数组
  const obj = {};
  b.forEach(k => {
    if(obj[k])
      obj[k]++;
    else
      obj[k] = 1;
  });
  console.log('obj:', obj);
  let max = 1, char = '';
  Object.keys(obj).map(k => {
    if(obj[k] > max) {
      max = obj[k];
      char = k;
    }
  });
  console.log('max:', max, ';char:', char);
}

方法三 

function getMaxChar3(str) {
  let obj = {};
  for (let i = 0; i < str.length; i++) {
    if(obj[str[i]] == null) {
      obj[str[i]] = 1;
    } else {
      obj[str[i]]++;
    }
  }
  console.log('obj:', obj);
  let max = 0;
  let maxChar = '';
  for (let key in obj) {
    if(obj[key] > max) {
      max = obj[key];
      maxChar = key;
    }
  }
  console.log('max:', max, ';char:', maxChar);
}

你可能感兴趣的:(javascript,通用方法,javascript)