找出出现次数最多的元素及它的次数

116 阅读1分钟

image.png

先上代码

  let str = "qwertasdbjsaxbhsvhj";
      let obj = {};
      for (let i = 0; i < str.length; i++) {
        if (!obj[str.charAt(i)]) {
          obj[str.charAt(i)] = 1;
        } else {
          obj[str.charAt(i)]++;
        }
      }
      console.log(obj);

      let max = 0;
      name = "";
      for (let i in obj) {
        if (obj[i] > max) {
          max = obj[i];
          name = i;
        }
      }

      console.log("出现次数最多的是:" + name + "出现了" + max + "次"); 

解析

 
      let str = "qwertasdbjsaxbhsvhj";
      let obj = {};
      for (let i = 0; i < str.length; i++) {
        // 对象中不存在这个元素
        if (!obj[str.charAt(i)]) {
          // 那在这个对象里面,这个元素的就为1
          obj[str.charAt(i)] = 1;
        } else {
          // 否则,对象中这个元素的值+1
          obj[str.charAt(i)]++;
        }
      }
      console.log(obj);

      let max = 0;
      name = "";
      for (let i in obj) {
        // 使用冒泡排序判断大小
        if (obj[i] > max) {
          max = obj[i];
          name = i;
        }
      }

      console.log("出现次数最多的是:" + name + "出现了" + max + "次"); 

有一个缺陷就是,当最多次数的元素是两个时,那输出的是排在前面的那个元素。 参考文献:

www.cnblogs.com/hubovv/p/10…

yige.org/js/jsref_ch…