js输入任意字符串,统计各个字符的个数

js输入任意字符串,统计各个字符的个数

function count(str) {
     
    let newStr = '';
    let map = new Map();
    for(let i=0; i<str.length; i++){
     
        let c = str.substr(i,1);
        if(c.trim()){
       //空字符不算
            newStr += c;
            let num = 1;
            if(map.has(c)){
     
                num = parseInt(map.get(c)) + 1;
            }
            map.set(c, num)
        }
    }
    let obj= Object.create(null);
    for (let[k,v] of map) {
     
       obj[k] = v;
    }
    console.log(obj);
}

count('dhjsfdjfdhjhhhhhhh322as') 
//输出:{2: 2, 3: 1, d: 3, h: 9, j: 3, s: 2, f: 2, …}

你可能感兴趣的:(js,javascript,算法,js,算法)