js quiz

找出字符串出现最多次数的字符

var str = "sakfjksdjffffffff";

function getMostFrequenceLetter(str){
    var i = 0,
        len = str.length,
        dict = {},
        list = [];
    for (; i<len; i++) {
        var c = str[i];//char
        dict[c] = dict[c]? (dict[c]+1):1;
        list[dict[c]] = c;
    };

    return list.slice(-1);
}

getMostFrequenceLetter(str);

数组去重

function onlyUnique(value, index, self) { 
    return self.indexOf(value) === index;
}

// usage example:
var a = ['a', 1, 'a', 2, '1'];
var unique = a.filter( onlyUnique )

求对称数

function isSymmetry (num) {
    return num.toString().split('').reverse().join('') == num
}

字符串模板方法

if (!String.prototype.supplant) {
    String.prototype.supplant = function (o) {
        return this.replace(
            /\{([^{}]*)\}/g,
            function (a, b) {
                var r = o[b];
                return typeof r === 'string' || typeof r === 'number' ? r : a;
            }
        );
    };
}
param = {domain: 'valvion.com', media: 'http://media.valvion.com/'};
url = "{media}logo.gif".supplant(param);//"http://media.valvion.com/logo.gif".

支持嵌套

if (!String.prototype.supplant) {
    String.prototype.supplant = function(o) {
        return this.replace(
            /\{([^{}]*)\}/g,
            function(a, b) {
                var p = b.split('.');
                var r = o;
                try {
                    p.forEach(function(v, k) {
                        r = r[v]
                    })
                } catch (e) {
                    r = a;
                }
                return typeof r === 'string' || typeof r === 'number' ? r : a;
            }
        );
    };
}
param = {domain: 'valvion.com', c:{a:{media: 'http://media.valvion.com/'}};
url = "{c.a.media}logo.gif".supplant(param);//"http://media.valvion.com/logo.gif".

Published: October 11 2013