javascript公共方法

1、获取字符的长度

getByteLen(val) {
        var len = 0;
        for (var i = 0; i < val.length; i++) {
            var a = val.charAt(i);
            if (a.match(/[^\x00-\xff]/ig) != null) {
                len += 2;
            } else {
                len += 1;
            }
        }
        return len;
    },

   2、 格式化金额,单位:分(eg:430分=4.30元)
    formatFee(fee, suffix = '') {
        if (!fee) {
            return 0;
        }
        return Number(fee).toFixed(2) + suffix;
    },
    3、格式化公里(eg:3000 = 3公里)
    formatMileage(mileage, text) {
        if (!mileage) {
            return 0;
        }
        if (mileage >= 1000) {
            text = text || " km";
            return Math.floor(mileage / 100) / 10 + text;
        } else {
            text = text || " m";
            return mileage + text;
        }
    },
    4、 隐藏手机号中间4位
    formatPhone(phone) {
        phone += '';
        return phone.replace(/(\d{3})\d*(\d{4})/g, '$1***$2')
    },
   5、隐藏身份证号中11位
    formatIdentity(number) {
        number += '';
        return number.replace(/(\d{3})\d*(\d{4})/g, '$1***********$2')
    },

6、moment格式化时间
    momentFormat(time,format='YYYY-MM-DD HH:mm:ss') {
        return moment(time).format(format)
    },

7、 listToTree

listToTree(data = []) {
        data = data.map(d => ({...d, key: d._id || d.cat_id}));
        const isHasChild = id => data.some(m => m.parent_id === id);
        const loopMenus = (menus) => {
            menus.forEach(it => {
                if (isHasChild(it._id || it.cat_id)) {
                    it.children = [];
                    data.forEach(it2 => {
                        if (it2.parent_id === (it._id || it.cat_id)) {
                            it.children.push(it2);
                        }
                    });
                    loopMenus(it.children);
                }
            })
        }
        const getTopLevel = m => m.parent_id == 0;
        let menus = data.filter(getTopLevel);
        loopMenus(menus);
        return menus
    }

8、设置头部信息

    setMetaAboutSeoFun(data) {
        let description = document.querySelector('meta[name="description"]'),
            keywords = document.querySelector('meta[name="keywords"]');
        description["content"] = data.summary;
        keywords["content"] = data.keyword;
        if (data.title) {
            document.title = data.title;
        }
    },

9、对象转为formData格式

    obj2FormData(param) {
        const formData = new FormData();
        Object.keys(param).forEach((key) => {
            formData.append(key, param[key]);
        });
        return formData;
    },

10、  去除数组中的值为false值

  bouncer(arr) {
        return arr.filter(function (val) {
            return !(!val || val === "");
        });
    },

11、限制输入框的字符长度

    compositionInput(id, that) {
        let inputLock = false;
        that.timer = setTimeout(() => {
            let nickNameId = document.getElementById(id);
            if (nickNameId) {
                nickNameId.addEventListener('compositionstart', () => {
                    inputLock = true;
                });
                nickNameId.addEventListener('compositionend', () => {
                    inputLock = false;
                    var value = nickNameId.value,
                        maxlength = nickNameId.getAttribute('maxlength');
                    if (this.byteLen(value) > maxlength) {
                        nickNameId.value = this.getMaxlen(value, maxlength);
                    }
                });
                nickNameId.addEventListener('input', () => {
                    if (!inputLock) {
                        var value = nickNameId.value,
                            maxlength = nickNameId.getAttribute('maxlength');
                        if (this.byteLen(value) > maxlength) {
                            nickNameId.value = this.getMaxlen(value, maxlength);
                        }
                    }
                });
            }
        }, 1000);
    },
     byteLen(str) {
        //正则取到中文的个数,然后len*count+原来的长度。不用replace
        str += '';
        var tmp = str.match(/[^\x00-\xff]/g) || [];
        return str.length + tmp.length;
    },
    getMaxlen(str, maxlen) {
        var sResult = '', L = 0, i = 0, stop = false, sChar;
        if (str.replace(/[^\x00-\xff]/g, 'xxx').length <= maxlen) {
            return str;
        }
        while (!stop) {
            sChar = str.charAt(i);
            L += sChar.match(/[^\x00-\xff]/) ? 2 : 1;
            if (L > maxlen) {
                stop = true;
            } else {
                sResult += sChar;
                i++;
            }
        }
        return sResult;
    },

使用方法

 <Input maxLength={30} type="text" onBlur={this.checkoutNicknameBlur}/>

  compositionInput('nick_name', this);

12、promise的使用

registerCheckHttp = (key, type) => {  // 检查用户昵称、手机、邮箱是否已存在
        return new Promise((resolve, reject) => {
            axiosHttp(`api/WebSite/Register/Check?key=${key}&keyType=${type}`, '', 'GET').then((res) => {
                resolve(res);
            }).catch(e => {
                reject(e)
            })
        });
    };

    this.registerCheckHttp(value, NICK_NAME).then(res => {
       
        }).catch(e => {

        });

13、base64封装的加密和解密函数

  base64Function() {  
        // private property
        let _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

        // public method for encoding
        this.encode = function (input) {
            var output = "";
            var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
            var i = 0;
            input = _utf8_encode(input);
            while (i < input.length) {
                chr1 = input.charCodeAt(i++);
                chr2 = input.charCodeAt(i++);
                chr3 = input.charCodeAt(i++);
                enc1 = chr1 >> 2;
                enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
                enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
                enc4 = chr3 & 63;
                if (isNaN(chr2)) {
                    enc3 = enc4 = 64;
                } else if (isNaN(chr3)) {
                    enc4 = 64;
                }
                output = output +
                    _keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
                    _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
            }
            return output;
        };

        // public method for decoding
        this.decode = function (input) {
            var output = "";
            var chr1, chr2, chr3;
            var enc1, enc2, enc3, enc4;
            var i = 0;
            input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
            while (i < input.length) {
                enc1 = _keyStr.indexOf(input.charAt(i++));
                enc2 = _keyStr.indexOf(input.charAt(i++));
                enc3 = _keyStr.indexOf(input.charAt(i++));
                enc4 = _keyStr.indexOf(input.charAt(i++));
                chr1 = (enc1 << 2) | (enc2 >> 4);
                chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
                chr3 = ((enc3 & 3) << 6) | enc4;
                output = output + String.fromCharCode(chr1);
                if (enc3 != 64) {
                    output = output + String.fromCharCode(chr2);
                }
                if (enc4 != 64) {
                    output = output + String.fromCharCode(chr3);
                }
            }
            output = _utf8_decode(output);
            return output;
        };

        // private method for UTF-8 encoding
        let _utf8_encode = function (string) {
            string = string.replace(/\r\n/g, "\n");
            var utftext = "";
            for (var n = 0; n < string.length; n++) {
                var c = string.charCodeAt(n);
                if (c < 128) {
                    utftext += String.fromCharCode(c);
                } else if ((c > 127) && (c < 2048)) {
                    utftext += String.fromCharCode((c >> 6) | 192);
                    utftext += String.fromCharCode((c & 63) | 128);
                } else {
                    utftext += String.fromCharCode((c >> 12) | 224);
                    utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                    utftext += String.fromCharCode((c & 63) | 128);
                }

            }
            return utftext;
        };

        // private method for UTF-8 decoding
        let _utf8_decode = function (utftext) {
            var string = "";
            var i = 0;
            var c = 0, c1 = 0, c2 = 0, c3 = 0;
            while (i < utftext.length) {
                c = utftext.charCodeAt(i);
                if (c < 128) {
                    string += String.fromCharCode(c);
                    i++;
                } else if ((c > 191) && (c < 224)) {
                    c2 = utftext.charCodeAt(i + 1);
                    string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                    i += 2;
                } else {
                    c2 = utftext.charCodeAt(i + 1);
                    c3 = utftext.charCodeAt(i + 2);
                    string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                    i += 3;
                }
            }
            return string;
        }
    }

使用方法

this.base64 = new base64Function();

this.base64.decode(pass_word),//解密

this.base64.encode(pass_word),//加密

14、替换地址栏中的url

window.history.replaceState(null, null, '/?keyword='+item)

15、cookie设置和获取

const {cookieExpires, cookieName, cookieValue} = res.data;
this.pageInfo.cookieValue = cookieValue;
var exp = new Date();
exp.setTime(exp.getTime() + cookieExpires * 60 * 1000);
document.cookie = `${cookieName}=${cookieValue};expires=${exp.toGMTString()}; path=/; samesite=lax`;

let cookie = document.cookie && document.cookie.split("=")[1];

16、antd中表单中的应用

   hasErrors(fieldsError) {
        // console.log(fieldsError);
        return Object.keys(fieldsError).some(field => fieldsError[field]);
    },
    hasValues(value) {
        // console.log(value);
        if (JSON.stringify(value) === "{}") {
            return true
        }
        let item = null;
        return Object.keys(value).some(field => {
            if (value[field] === true) {
                return false
            }
            item = value[field] && value[field].trim(); //undefined ,'  '
            return item === '' || item === undefined; //true
        });
    },

使用方法

      const {getFieldsError, getFieldsValue} = this.props.form;
        let disabled = hasValues(getFieldsValue()) === true || hasErrors(getFieldsError()) === true;

17、获取地址栏中search转化为object

getUrlSearchParam = () => {
    let {search} = window.location;
    if (search.indexOf('utm_campaign') < 0) {
        return
    }
    let obj = {}, searchArr = search.substring(1,).split('&');
    for (let i = 0; i < searchArr.length; i++) {
        let [name, value] = searchArr[i].split('=');
        obj[name] = value;
    }
    window.sessionStorage.setItem('recordParam', JSON.stringify(obj));
};
18、把一个数组分割成二维数组,而且每个数组长度一样,不一样过滤掉
function group(array, subGroupLength) {
    let index = 0, newArray = [];
    while (index < array.length && index + subGroupLength < array.length) {
        newArray.push(array.slice(index, index += subGroupLength));
    }
    return newArray;
}

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值