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);