javascript 常见工具函数(五)

发布时间:2024年01月03日

41.深度拷贝对象:

  static deepCopyObj$(obj) {
        var result = Array.isArray(obj) ? [] : {};
        for (var key in obj) {
            if (obj.hasOwnProperty(key)) {
                if (typeof obj[key] === 'object' && obj[key] !== null) {
                    result[key] = Utils$.deepCopyObj$(obj[key]);   //递归复制
                } else {
                    result[key] = obj[key];
                }
            }
        }
        return result;
    }

42.对象属性和值,随机对象中的属性:

 /** 随机对象中的一个属性值 */
    static randomObj$(obj) {
        var keys = Object.keys(obj)
        let targetKey = keys[keys.length * Math.random() << 0];
        return obj[targetKey];


    };

43.比较两个数组是否相同:

static arrDiff(arr1, arr2) {
        let isNaN = Number.isNaN;
        return arr1.reduce(function (previous, i) {
            var found = arr2.findIndex(function (j) {
                return j === i || (isNaN(i) && isNaN(J));
            });
            return (found < 0 && previous.push(i), previous);
        }, []);
    };

44.字符串数组提取数字元素,并且转化为数组:

let showNumArr = this.zsConfig.zs_native_end_before_num.replace(/[^0-9]/ig,",").split(",");
showNumArr.shift();
showNumArr.pop();

45.字符串匹配 .jpg后缀以及.png后缀的图片地址:

regImgUrl$(str) {
        var reg = /http:\/\/.*?(gif|png|jpg)/gi;
        var reg2 = /https:\/\/.*?(gif|png|jpg)/gi;
        if (str.match(reg) && str.match(reg).length > 0) {
            return str.match(reg)[0];
        }
        if (str.match(reg2) && str.match(reg2).length > 0) {
            return str.match(reg2)[0];
        }
    }

46.计算时间戳间隔:

static calculateDiffTime$(start_time) {
        if (!parseInt(start_time)) return "-";
        var endTime = Math.round(new Date() / 1000);


        var timeDiff = endTime - start_time
        var day = parseInt(timeDiff / 86400);
        var hour = parseInt((timeDiff % 86400) / 3600);
        var minute = parseInt((timeDiff % 3600) / 60);


        day = day ? (day + '天') : 0;
        hour = hour ? (hour + "时") : 0;
        minute = minute ? (minute + "分") : 0;
        return day;   //注意这里返回的是字符串
    }

47.转化日期,时分秒格式,发送服务端用于:

 static dateFormat$(fmt, date) {
        let ret;
        const opt = {
            "y+": date.getFullYear().toString(),        // 年
            "M+": (date.getMonth() + 1).toString(),     // 月
            "d+": date.getDate().toString(),            // 日
            "h+": date.getHours().toString(),           // 时
            "m+": date.getMinutes().toString(),         // 分
            "s+": date.getSeconds().toString()          // 秒
            // 有其他格式化字符需求可以继续添加,必须转化成字符串
        };
        for (let k in opt) {
            ret = new RegExp("(" + k + ")").exec(fmt);
            if (ret) {
                fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
            };
        };
        return fmt;
    }

48.格式化数字:

 static formatNumber$(num) {
        if (isNaN(num)) return "0";
        if (num > 1000000) {
            num /= 1000000;
            if (num >= 100) {
                return Math.round(num) + "m"
            } else if (num >= 10) {
                num = num.toFixed(1);
                return num + "m"
            } else {
                num = num.toFixed(2);
                return num + "m"
            }
        } else if (num > 1000) {
            num /= 1000;
            if (num >= 100) {
                return Math.round(num) + "k"
            } else if (num >= 10) {
                num = num.toFixed(1);
                return num + "k"
            } else {
                num = num.toFixed(2);
                return num + "k"
            }
        } else {
            return Math.round(num);
        }
    }

49.身份证号判断是否成年;

 /**
    * 根据身份证号得到姓别和精确计算年龄
    */
    static analyzeIDCard$(IDCard){
       //获取用户身份证号码
       let userCard = IDCard;
       //如果身份证号码为undefind则返回空
       if(!userCard){
           return false;
       }
       //获取出生年月日
       let yearBirth = userCard.substring(6,10);
       let monthBirth = userCard.substring(10,12);
       let dayBirth = userCard.substring(12,14);
       //获取当前年月日并计算年龄
       let myDate = new Date();
       let monthNow = myDate.getMonth() + 1;
       let dayNow = myDate.getDate();
       let age = myDate.getFullYear() - yearBirth;
       if(monthNow < monthBirth || (monthNow == monthBirth && dayNow < dayBirth)){
           age--;
       }
       if (age >= 18) { return true; }
       return false;
   }

50.数字转中文:

  /**
     * 数字转中文
     * @param {*} num
     * @returns
     */
    static toChinesNum$(num) {
        let changeNum = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
        let unit = ["", "十", "百", "千", "万"];
        num = parseInt(num);
        let getWan = (temp) => {
            let strArr = temp.toString().split("").reverse();
            let newNum = "";
            for (var i = 0; i < strArr.length; i++) {
                newNum = (i == 0 && strArr[i] == 0 ? "" : (i > 0 && strArr[i] == 0 && strArr[i - 1] == 0 ? "" : changeNum[strArr[i]] + (strArr[i] == 0 ? unit[0] : unit[i]))) + newNum;
            }
            return newNum;
        }
        let overWan = Math.floor(num / 10000);
        let noWan = num % 10000;
        if (noWan.toString().length < 4) { noWan = "0" + noWan; }
        return overWan ? getWan(overWan) + "万" + getWan(noWan) : getWan(num);
    }

文章来源:https://blog.csdn.net/woshiyuyanjia/article/details/135358839
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。