JS计算每个字符出现的次数

今天在优化代码的时候,需要计算每个字符出现的次数,自己写了一个,但是代码过长,效率不高,百度了很久,没有找到什么合适,在一位好友的帮助下:淡描温情

 写下下面代码 

 //计算每个字符出现的次数
    var t = "stringthatresults", i = 0, len = t.length,
    result = [],//输出结果
    hash = {};//hash表,用于记录是否重复计算字符
    for (i = 0; i < len; i++) {
        if (!hash[t.charAt(i)]) {
            hash[t.charAt(i)] = true;
            //分割当前字符本身,来获取出现次数
            result.push(t.charAt(i) + ":" + (t.split(t.charAt(i)).length - 1));
        }
    }
    document.writeln(JSON.stringify(result) + "<br />");



    var a = "stringthatresults";
    var b = {};
    var c = null;
    for (var i = 0; i < a.length; i++) {
        if (!isNaN(b[a.charAt(i)]++) || (b[a.charAt(i)] = 1)) {
            c = b[a.charAt(i)] > c ? a.charAt(i) : c;
        }
    }
    document.writeln(JSON.stringify(b) + "<br />");



    result = [];
    var count = 0, tmp = "", arr = t.split("");
    for (i = 0; i < len; i++) {

        //替换当前字符,再通过与原有字符串长度做加减,来获取出现次数
        tmp = t.replace(new RegExp(arr[i], "g"), "");
        count = t.length - tmp.length;



        if (count > 0) {
            result.push(arr[i] + ":" + count);
        }
        t = tmp;
    }
    document.writeln(JSON.stringify(result));

 

  结果     

["s:3","t:4","r:2","i:1","n:1","g:1","h:1","a:1","e:1","u:1","l:1"]
{"s":3,"t":4,"r":2,"i":1,"n":1,"g":1,"h":1,"a":1,"e":1,"u":1,"l":1}

["s:3","t:4","r:2","i:1","n:1","g:1","h:1","a:1","e:1","u:1","l:1"]

应该还有更好的思路,希望大家多多提建议。个人偏向第一种写法

posted @ 2015-06-17 23:54  飘落风尘鬓擒雪  阅读(359)  评论(0编辑  收藏  举报