js 查找數組中某個字符出現的次數


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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM