在字符串找到出最多出现字符


<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        //将字符串出现的字符和次数存在对象countStr中
        //保存形式为key等于字符value等于次数
        //for循环字符字符 如果无法根据字符访问这个对象属性说明没有出现过
        //没出现 countStr[str[i]] =1; 否则countStr[str[i]]++;
        //最后for of 这个对象哪个属性值大

        var str = 'aaaabbbbbbbbbbbbbasdx,cxcvx';
        function findMostChar(str) {
            let countStr = {};
            for (let i = 0; i < str.length; i++) {

                // let existKey = false;
                // for (let o = 0; o < Object.keys(countStr).length; o++) {
                //     if (str[i] == Object.keys(countStr)[o]) {
                //         existKey = true;
                //         ++countStr[str[i]];
                //     }
                // }
                // if (!existKey) {
                //     //初始化一次
                //     countStr[str[i]] = 1;
                // }

                // //以上可以简化
                // if (countStr[str[i]]) {//如果是undefined 没有出现过
                //     countStr[str[i]]++;
                // } else {
                //     countStr[str[i]] = 1;
                // }

                //又或者
                let char = str.charAt(i);//str[i]
                if (countStr[char]) {//如果是undefined 没有出现过
                    countStr[char]++;
                } else {
                    countStr[char] = 1;
                }

            }

            let num = 0;//最多出现的次数
            let key = '';//最多出现的字符
            for (let i of Object.keys(countStr)) {
                if (countStr[i] > num) {
                    num = countStr[i];
                    key = i;
                }
            }

            let fRes = {};
            fRes[key] = num;
            return fRes;

        }

        let log = findMostChar(str);
    </script>
</body>

</html>

文章作者: iamfugui
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 iamfugui !
评论
  目录