当前位置:网站首页>Case: count the most characters and times

Case: count the most characters and times

2022-06-25 19:42:00 Guguwai

<script>
        // Take out each character and add it to  o  As attribute , Then judge whether the attribute exists , There is an assignment of 1, Again +1;
        var str = 'abcoefoxyozzopp';
        var o = {};
        for (i = 0; i < str.length; i++) {
            var chars = str.charAt(i);
            if (o[chars]) {//chars Is every character of the string 
                o[chars]++;
            } else {
                o[chars] = 1;// Assign a value to a property 
            }
        }
        console.log(o);
        // Traversing objects 
        var max = 0;
        var ch = '';
        for (var k in o) {
            //k What you get is the attribute name 
            //  o[k] What you get is the attribute value 
            if (o[k] > max) {
                max = o[k];
                ch = k;
            }
        }
        console.log(max);
        console.log(' The most common characters are ' + ch);

    </script>

原网站

版权声明
本文为[Guguwai]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202190516580722.html