1. js 查找数组中某个字符出现的次数
代码示例
let arr = ['asd', 'green', 'yeadt', 'red', 'wati', 'red', 'red'] let index = arr.indexOf('red') let num = 0 while (index !== -1) { num++ console.log('red 的下标为' + index); index = arr.indexOf('red', index + 1) } console.log('总共出现的次数为' + num);
注意 : 也可以查找字符串道理一样
2. 统计出现次数最多的字符
// 核心算法: 利用 charAt() 遍历这个字符串 // 把每个字符串都储存给对象, 如果对象没有该属性, 就为1 , 如果存在了就 +1 // 遍历对象, 得到最大值和该字符 var str = 'abcoefoxyozzopp'; var obj = {}; for (var i = 0; i < str.length; i++) { var chars = str.charAt(i); // chars 是字符串的每一个字符 // 判断 字符串中出现的次数 if (obj[chars]) { // obj[chars] 得到的是属性值 obj[chars]++ } else { obj[chars] = 1 } } console.log(obj); let max = 0; let ch = ''; for (let k in obj) { if (max < obj[k]) { max = obj[k] ch = k; } } console.log(max, ch);