模板引擎、字节转换、map函数

1. 模板引擎
var reg = /\$\{[a-zA-Z]+\}/g;
var tpl = "hello ${who}!";
var obj = {who:"world"};
function template(tpl,obj){
        var s = reg.exec(tpl);
        var s1 = s[0].slice(2,-1);
        document.write(tpl.replace(reg,obj[s1]));
    }
    //template(tpl,obj);
    template('Hello,${name}',{name:"hedahang"});
2. 字节转换
<pre>function bytesToSize(bytes) {
    if (bytes === 0) return '0 B';
    var k = 1024,
            sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
            i = Math.floor(Math.log(bytes) / Math.log(k));
    return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
}
console.log( bytesToSize(12345));</pre>
3. map函数
<pre>function map(arr,fun){
    var array = [];
    for(var i = 0;i<arr.length;i++){
        if( i == 0){
            array[i] = fun(0,arr[i]);
        }else{
            array[i] = fun(arr[i-1],arr[i])
        }
    console.log(array);
    }
}
map([1,2,3,4,5],function(o,i){return o + i;})</pre>