javascript狂想曲(二)

2017-08-16  本文已影响14人  我是上帝可爱多

今天带大家轻松一下,分享一下我们在日常开发中会经常用到的工具函数,绝对是干货,之后我会push到我的github仓库,供大家学习分享。

1 字符串操作

1-1 去除字符串空格
//去除空格  type 1-所有空格  2-前后空格  3-前空格 4-后空格
function trim(str,type){
    switch (type){
        case 1:return str.replace(/\s+/g,"");
        case 2:return str.replace(/(^\s*)|(\s*$)/g, "");
        case 3:return str.replace(/(^\s*)/g, "");
        case 4:return str.replace(/(\s*$)/g, "");
        default:return str;
    }
}
1-2 字母大小写切换
/*type
1:首字母大写   
2:首页母小写
3:大小写转换
4:全部大写
5:全部小写
 * */
//changeCase('asdasd',1)
//Asdasd
function changeCase(str,type)
{
    function ToggleCase(str) {
        var itemText = ""
        str.split("").forEach(
            function (item) {
                if (/^([a-z]+)/.test(item)) {
                    itemText += item.toUpperCase();
                }
                else if (/^([A-Z]+)/.test(item)) {
                    itemText += item.toLowerCase();
                }
                else{
                    itemText += item;
                }
            });
        return itemText;
    }

    switch (type) {
        case 1:
            return str.replace(/^(\w)(\w+)/, function (v, v1, v2) {
                return v1.toUpperCase() + v2.toLowerCase();
            });
        case 2:
            return str.replace(/^(\w)(\w+)/, function (v, v1, v2) {
                return v1.toLowerCase() + v2.toUpperCase();
            });
        case 3:
            return ToggleCase(str);
        case 4:
            return str.toUpperCase();
        case 5:
            return str.toLowerCase();
        default:
            return str;
    }
1-3 字符串指定替换
//replaceStr(字符串,字符格式, 替换方式,替换的字符(默认*))
function replaceStr(str, regArr, type,ARepText) {
    var regtext = '', Reg = null,replaceText=ARepText||'*';
    //replaceStr('18819322663',[3,5,3],0)
    //188*****663
    //repeatStr是在上面定义过的(字符串循环复制),大家注意哦
    if (regArr.length === 3 && type === 0) {
        regtext = '(\\w{' + regArr[0] + '})\\w{' + regArr[1] + '}(\\w{' + regArr[2] + '})'
        Reg = new RegExp(regtext);
        var replaceCount = repeatStr(replaceText, regArr[1]);
        return str.replace(Reg, '$1' + replaceCount + '$2')
    }
    //replaceStr('asdasdasdaa',[3,5,3],1)
    //***asdas***
    else if (regArr.length === 3 && type === 1) {
        regtext = '\\w{' + regArr[0] + '}(\\w{' + regArr[1] + '})\\w{' + regArr[2] + '}'
        Reg = new RegExp(regtext);
        var replaceCount1 = repeatSte(replaceText, regArr[0]);
        var replaceCount2 = repeatSte(replaceText, regArr[2]);
        return str.replace(Reg, replaceCount1 + '$1' + replaceCount2)
    }
    //replaceStr('1asd88465asdwqe3',[5],0)
    //*****8465asdwqe3
    else if (regArr.length === 1 && type == 0) {
        regtext = '(^\\w{' + regArr[0] +  '})'
        Reg = new RegExp(regtext);
        var replaceCount = repeatSte(replaceText, regArr[0]);
        return str.replace(Reg, replaceCount)
    }
    //replaceStr('1asd88465asdwqe3',[5],1,'+')
    //"1asd88465as+++++"
    else if (regArr.length === 1 && type == 1) {
        regtext = '(\\w{' + regArr[0] +  '}$)'
        Reg = new RegExp(regtext);
        var replaceCount = repeatSte(replaceText, regArr[0]);
        return str.replace(Reg, replaceCount)
    }
}
1-4 检测字符串
/checkType('165226226326','phone')
//false
//大家可以根据需要扩展
function checkType (str, type) {
    switch (type) {
        case 'email':
            return /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(str);
        case 'phone':
            return /^1[3|4|5|7|8][0-9]{9}$/.test(str);
        case 'tel':
            return /^(0\d{2,3}-\d{7,8})(-\d{1,4})?$/.test(str);
        case 'number':
            return /^[0-9]$/.test(str);
        case 'english':
            return /^[a-zA-Z]+$/.test(str);
        case 'chinese':
            return /^[\u4E00-\u9FA5]+$/.test(str);
        case 'lower':
            return /^[a-z]+$/.test(str);
        case 'upper':
            return /^[A-Z]+$/.test(str);
        default :
            return true;
    }
}
1-5金额转换
 //金额格式化
//formatMoney(1234567.456)  1,234,567.46
        var formatMoney = function(money, digit){
            var tpMoney = new Number(money);
            if(isNaN(tpMoney)){
                return '0.00';
            }

            tpMoney = tpMoney.toFixed(digit) + '';
            var re = /^(-?\d+)(\d{3})(\.?\d*)/;

            while(re.test(tpMoney)){
                tpMoney = tpMoney.replace(re, "$1,$2$3")
            }
            return tpMoney;
        }
1-6 获取location的参数
//getParam('www.miracle.com?name=qwe&&gender=male',gender)  male
var getParam = function(name) {
        var reg = new RegExp("(^|\\?|&)" + name + "=([^&]*)(\\s|&|$)", "i");
        if (reg.test(location.href)) {
            return unescape(RegExp.$2.replace(/\+/g, " "))
        } else {
            return null
        }
    };

2 数组操作

2-1 去重
//removeRepeatArray([1,1,2,2,3,3])  [1,2,3]
function removeRepeatArray(arr){
    return Array.from(new Set(arr))
}
2-2 返回数组(字符串)出现最多的几次元素和出现次数
//arr, rank->长度,默认为数组长度,ranktype,排序方式,默认降序
function getCount(arr, rank,ranktype){ 
    var obj = {}, k, arr1 = []
    //记录每一元素出现的次数
    for (var i = 0, len = arr.length; i < len; i++) {
        k = arr[i];
        if (obj[k]) {
            obj[k]++;
        }
        else {
            obj[k] = 1;
        }
    }
    //保存结果{el-'元素',count-出现次数}
    for (var o in obj) {
        arr1.push({el: o, count: obj[o]});
    }
    //排序(降序)
    arr1.sort(function (n1, n2) {
        return n2.count - n1.count
    });
    //如果ranktype为1,则为升序,反转数组
    if(ranktype===1){
        arr1=arr1.reverse();
    }
    var rank1 = rank || arr1.length;
    return arr1.slice(0,rank1);
}

2-3 筛选数组
/删除值为'val'的数组元素
//removeArrayForValue(['test','test1','test2','test','aaa'],'test','%')
//["aaa"]   带有'test'的都删除
    
//removeArrayForValue(['test','test1','test2','test','aaa'],'test')
//["test1", "test2", "aaa"]  //数组元素的值全等于'test'才被删除
function removeArrayForValue(arr,val,type){
    arr.filter(function(item){return type==='%'?item.indexOf(val)!==-1:item!==val})
}
2-4 对象数组的排序
//var arr=[{a:1,b:2,c:9},{a:2,b:3,c:5},{a:5,b:9},{a:4,b:2,c:5},{a:4,b:5,c:7}]
//arraySort(arr2,'a,b') a是第一排序条件,b是第二排序条件
//[{a:1,b:2,c:9},{a:2,b:3,c:5},{a:4,b:2,c:5},{a:4,b:5,c:7},{a:5,b:9}]
arraySort: function (arr, sortText) {
 if (!sortText) {
 return arr
 }
 var _sortText = sortText.split(',').reverse(), _arr = arr.slice(0);
 for (var i = 0, len = _sortText.length; i < len; i++) {
 _arr.sort(function (n1, n2) {
 return n1[_sortText[i]] - n2[_sortText[i]]
 })
 }
 return _arr;
}

3 番外篇

适配rem的解决方案

function getFontSize(){
    var doc=document,win=window;
    var docEl = doc.documentElement,
    resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
    recalc = function () {
        var clientWidth = docEl.clientWidth;
        if (!clientWidth) return;
        //如果屏幕大于750(750是根据我效果图设置的,具体数值参考效果图),就设置clientWidth=750,防止font-size会超过100px
        if(clientWidth>750){clientWidth=750}
        //设置根元素font-size大小
        docEl.style.fontSize = 100 * (clientWidth / 750) + 'px';
    };
    //屏幕大小改变,或者横竖屏切换时,触发函数
    win.addEventListener(resizeEvt, recalc, false);
    //文档加载完成时,触发函数
    doc.addEventListener('DOMContentLoaded', recalc, false);
}
//使用方式很简单,比如效果图上,有张图片。宽高都是100px;
//样式写法就是
img{
    width:1rem;
    height:1rem;
}
//这样的设置,比如在屏幕宽度大于等于750px设备上,1rem=100px;图片显示就是宽高都是100px
//比如在iphone6(屏幕宽度:375)上,375/750*100=50px;就是1rem=50px;图片显示就是宽高都是50px;

封装抖动函数

//运动的dom元素  属性 结束回调
function shake(obj,attr,endfn) {
        var arr = [];
        for (var i = 20; i > 0; i -= 2)
        {
            arr.push(i,-i);
        }
        arr.push(0);
        clearInterval(obj.shaker);
        var index = 0 ;
        obj.shaker = setInterval(function(){
            var speed = (parseInt(getStyle(obj,attr))+arr[index]);
            obj.style[attr] = speed +"px";
            ++index;
            if(index==arr.length)
            {
                clearInterval(obj.shaker);
                endfn&&endfn();
            }
        },10)
    }

封装一个ajax轮询:

(function(host, name, Event, undefined){
    var defConfig = {
        url:'/message.php',
        dataType:'json',
        method:'post',
        //间隔时间
        looptime:5 * 1000
    };
    Games = host.Games;

    var pros = {
        //初始化
        init: function(cfg){
            var me = this;
            me.timer = null;
        },
        start:function(){
            var me = this,cfg = me.defConfig,ajaxCfg = {};
            ajaxCfg = $.extend({}, cfg);
            ajaxCfg['success'] = function(data){
                me.fireEvent('beforeSuccess', data);
                me.success(data);
                me.fireEvent('afterSuccess', data);
            };
            ajaxCfg['error'] = function(xhr, type){
                me.fireEvent('beforeError', xhr ,type);
                me.error(xhr, type);
                me.fireEvent('afterError', xhr ,type);
            };
            ajaxCfg['complete'] = function(){
                me.fireEvent('beforeComplete');
                me.complete();
                me.fireEvent('afterComplete');
            };
            ajaxCfg['data'] = me.getParams();
            //console.log(me.getParams());
            $.ajax(ajaxCfg);
        },
        pause:function(){
            clearTimeout(this.timer);
        },
        loop:function(){
            var me = this,cfg = me.defConfig;
            if(cfg.looptime > 0){
                clearTimeout(me.timer);
                me.timer = setTimeout(function(){
                    me.start();
                }, cfg.looptime);
            }
        },
        getParams:function(){
            var params = [
                    {
                        'type':'account'
                    },
                    {
                        'type':'bets'
                    },
                    {
                        'type':'traces'
                    }
            ];
            return {'params':params};
        },
        success:function(data){
            this.loop();
        },
        error:function(xhr, type){
            this.loop();
        },
        complete:function(){

        }
    }

    var Main = host.Class(pros, Event);
        Main.defConfig = defConfig;
    host[name] = Main;

})(bomao, "Alive",  bomao.Event);

这个可是我们的内部代码。。。
如何使用:

var MSG = new bomao.Alive({
                        url: Games.getCurrentGame().getGameConfig().getInstance().getPollBetInfoUrl(),
                        cache:false,
                        dataType:'json',
                        method:'get',
                        // looptime:5 * 1000
                        looptime:10 * 1000
                });

                MSG.addEvent('afterSuccess', function(e, data){
                    var me = this,cfg = me.defConfig;
                        if(!checkUserTimeout(data)){
                            return;
                        }
                        if(Number(data['isSuccess']) == 1){
                            var results = data['data'];
                            $.each(results, function(){
                                switch(this['type']){
                                    case 'bets':
                                        updateBets(this['data']);
                                    break;
                                    case 'traces':
                                        updateTraces(this['data']);
                                    break;
                                    default:
                                    break;
                                }
                            });
                        }

好了,稍后我会把地址传上来。。。

上一篇下一篇

猜你喜欢

热点阅读