JS演算法——統計字元數量

Jsp發表於2018-05-29

function charCount( str ) {
    var obj = {},
        len = str.length,
        i = 0;

    for ( ; i < len; i++ ) {
        var val = str.charAt(i);

        if ( obj[val] && obj[val].value === val ) {
            obj[val].count++;
        }
        else {
            obj[val] = {};
            obj[val].count = 1;
            obj[val].value = val;
        }
    }

    for ( var key in obj ) {
        console.log( key + ' is ' + obj[key].count );
    }

    return obj;
}
複製程式碼


相關文章