检索字符串中出现次数最多的字符!!!

1.创建html将js引入



  
    
    
    Document
  
  
  
    
    
  
  

2.编写js代码

let str = "abacdkcaac";  
let charCount = {};  
  
for (let i = 0; i < str.length; i++) {  
  let char = str[i];  
  if (charCount[char]) {  
    charCount[char]++;  
  } else {  
    charCount[char] = 1;  
  }  
}  
  
let maxCount = 0;  
let maxChar = '';  
for (let char in charCount) {  
  if (charCount[char] > maxCount) {  
    maxCount = charCount[char];  
    maxChar = char;  
  }  
}  
  
console.log("出现次数最多的字符为:",maxChar); // 输出 "a"

3.查看运行结果:(首先F12打开控制台,即可查看结果!!!)

检索字符串中出现次数最多的字符!!!_第1张图片

你可能感兴趣的:(javascript,前端,开发语言,vscode)