阅读 403

项目应用-javascript-封装工具类

数字转字符

export function formatNumber(n) {
    const str = n.toString()
    return str[1] ? str : `0${str}`
}
复制代码

判断是否包含特殊符号 含有特殊字符包括空格返回 true

export function isCharacters(val) {
    if (val.match(/^[a-zA-Z0-9\u4e00-\u9fa5]+$/g)) {
        return false;
    } else {
        return true
    }

};
复制代码

判断是否包含表情

export function isEmoji(substring) {
    for (var i = 0; i < substring.length; i++) {
        var hs = substring.charCodeAt(i);
        if (0xd800 <= hs && hs <= 0xdbff) {
            if (substring.length > 1) {
                var ls = substring.charCodeAt(i + 1);
                var uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                if (0x1d000 <= uc && uc <= 0x1f77f) {
                    return true;
                }
            }
        } else if (substring.length > 1) {
            var ls = substring.charCodeAt(i + 1);
            if (ls == 0x20e3) {
                return true;
            }
        } else {
            if (0x2100 <= hs && hs <= 0x27ff) {
                return true;
            } else if (0x2B05 <= hs && hs <= 0x2b07) {
                return true;
            } else if (0x2934 <= hs && hs <= 0x2935) {
                return true;
            } else if (0x3297 <= hs && hs <= 0x3299) {
                return true;
            } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 ||
                hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b ||
                hs == 0x2b50) {
                return true;
            }
        }
    }
}
复制代码

判断手机号是否正确

export function testPhone(phone) {
    let phoneReg = /(^1[3|4|5|6|7|8|9]\d{9}$)|(^09\d{8}$)/;
    return phoneReg.test(phone);
}

复制代码

判断邮箱

export function testEmail(email) {
    var reg = new RegExp("^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$");
    return reg.test(email);
}

复制代码

判断身份证

export function idCardCheck(idNo) {
    var regIdNo = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
    if (!regIdNo.test(idNo)) {
        return false;
    } else {
        return true;
    }
}
复制代码

两个数组求差

export function diff(arr1, arr2) {
    var newArr = [];
    var arr3 = [];
    for (var i = 0; i < arr1.length; i++) {
        if (arr2.indexOf(arr1[i]) === -1)
            arr3.push(arr1[i]);
    }
    var arr4 = [];
    for (var j = 0; j < arr2.length; j++) {
        if (arr1.indexOf(arr2[j]) === -1)
            arr4.push(arr2[j]);
    }
    newArr = arr3.concat(arr4);
    return newArr;
}

复制代码

计算评分(多少星星)

export function starNum(num) {
    let fill = [];
    let half = [];
    let empty = [];

    let fillNum = parseInt(num);
    let halfNum = 0;
    if (num % 1) halfNum = 1;
    let emptyNum = 5 - fillNum - halfNum;

    for (let i = 0; i < fillNum; i++) {
        fill.push(1);
    }
    for (let i = 0; i < halfNum; i++) {
        half.push(1);
    }
    for (let i = 0; i < emptyNum; i++) {
        empty.push(1);
    }

    let obj = {
        fill: fill,
        half: half,
        empty: empty
    }
    return obj;
}

复制代码

根据经纬度计算两地之差

export function distance(la1, lo1, la2, lo2) {
    var La1 = la1 * Math.PI / 180.0;
    var La2 = la2 * Math.PI / 180.0;
    var La3 = La1 - La2;
    var Lb3 = lo1 * Math.PI / 180.0 - lo2 * Math.PI / 180.0;
    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(La3 / 2), 2) + Math.cos(La1) * Math.cos(La2) * Math.pow(Math.sin(Lb3 / 2), 2)));
    s = s * 6378.137;
    s = Math.round(s * 10000) / 10000;
    s = s.toFixed(2);
    return s;
}
复制代码

判断环境(web-view)

export function isMiniProgram() {
    var ua = navigator.userAgent.toLowerCase()
    var envType = '#'

    if (ua.match(/MicroMessenge/i) == 'micromessenger') {
        wx.miniProgram.getEnv(function(res) {
            if (res.miniProgram) { // 小程序环境下逻辑
                envType = true
            } else { // 非小程序环境下逻辑
                envType = false
            }
        })
    } else { // 非微信环境逻辑
        envType = false
    }
    return envType
}
复制代码

数组去重


export function unique(arr) {
    var res = [];
    var json = {};
    for (var i = 0; i < arr.length; i++) {
        if (!json[arr[i]]) {
            res.push(arr[i]);
            json[arr[i]] = 1;
        }
    }
    return res;
}
复制代码

格式时间

export function formatDate() {
    Date.prototype.pattern = function(fmt) {
        var o = {
            "M+": this.getMonth() + 1, //月份
            "d+": this.getDate(), //日
            "h+": this.getHours() % 12 == 0 ? 12 : this.getHours() % 12, //小时
            "H+": this.getHours(), //小时
            "m+": this.getMinutes(), //分
            "s+": this.getSeconds(), //秒
            "q+": Math.floor((this.getMonth() + 3) / 3), //季度
            S: this.getMilliseconds() //毫秒
        };
        var week = {
            "0": "/u65e5",
            "1": "/u4e00",
            "2": "/u4e8c",
            "3": "/u4e09",
            "4": "/u56db",
            "5": "/u4e94",
            "6": "/u516d"
        };
        if (/(y+)/.test(fmt)) {
            fmt = fmt.replace(
                RegExp.$1,
                (this.getFullYear() + "").substr(4 - RegExp.$1.length)
            );
        }
        if (/(E+)/.test(fmt)) {
            fmt = fmt.replace(
                RegExp.$1,
                (RegExp.$1.length > 1 ?
                    RegExp.$1.length > 2 ?
                    "/u661f/u671f" :
                    "/u5468" :
                    "") + week[this.getDay() + ""]
            );
        }
        for (var k in o) {
            if (new RegExp("(" + k + ")").test(fmt)) {
                fmt = fmt.replace(
                    RegExp.$1,
                    RegExp.$1.length == 1 ?
                    o[k] :
                    ("00" + o[k]).substr(("" + o[k]).length)
                );
            }
        }
        return fmt;
    };

    // let date = new Date();
    // window.alert(date.pattern("yyyy-MM-dd hh:mm:ss"));
};

export function formatTime(now) {
    var year = now.getFullYear();
    var month = now.getMonth() + 1;
    var date = now.getDate();
    var hour = now.getHours();
    var minute = now.getMinutes();
    var second = now.getSeconds();
    return year + "-" + (month >= 10 ? month : '0' + month) + "-" + (date >= 10 ? date : '0' + date) +
        " " + (hour >= 10 ? hour : '0' + hour) + ":" + (minute >= 10 ? minute : '0' + minute) + ":" + (second >= 10 ? second : '0' + second);
}

export function formatTimeTwo(number, format) {

    var formateArr = ['Y', 'M', 'D', 'h', 'm', 's'];
    var returnArr = [];

    var date = new Date(number);
    returnArr.push(date.getFullYear());
    returnArr.push(formatNumber(date.getMonth() + 1));
    returnArr.push(formatNumber(date.getDate()));

    returnArr.push(formatNumber(date.getHours()));
    returnArr.push(formatNumber(date.getMinutes()));
    returnArr.push(formatNumber(date.getSeconds()));

    for (var i in returnArr) {
        format = format.replace(formateArr[i], returnArr[i]);
    }
    return format;
}
复制代码