前端常用工具类js代码块

目录

1、格式化时间格式

2、处理字符串长度

3、格式化数字字符串

4、二维数组去重


1、格式化时间格式

function getFormatMonth(type) {
    var date = new Date();
    var seperator1 = "-";
    var seperator2 = ":";
    var month;
    if (type == "preMonth") {
        month = date.getMonth();
    } else {
        month = date.getMonth() + 1;
    }
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }

    var ti;
    if (type == "preMonth") {
        ti = "00:00:00";
    } else {
        ti = "23:59:59";
    }
    var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate +
        " " + ti;
    return currentdate;
}

/*
参数:type如果为“preMonth”则处理为上个月的时间,否则为当前时间
效果:返回值时间格式“2019-09-16 14:20:00”或者“2019:09:16 14:20:00”
*/

2、处理字符串长度

function dealStrLength(strVariable, len) {
    var tmpStr = strVariable
    if (strVariable.length > len) {
        tmpStr = strVariable.substring(0, len) + "..."
    }
    return tmpStr
}

/*
参数:strVariable->需要处理的字符串,len->截取的超度
效果:如果字符串超过设定的长度,超过的部分则被改为“...”拼接在字符串的后面
*/

3、格式化数字字符串

function formatNumber(num) {
    var tempNum = parseInt(num).toString();
    var len = tempNum.length;
    if (len <= 3) {
        return tempNum;
    }
    var res = len % 3;
    return res > 0 ? tempNum.slice(0, res) + "," +tempNum.slice(res, len).match(/\d{3}/g).join(",") : tempNum.slice(res, len).match(/\d{3}/g).join(",");
}

/*
参数:num->待处理的数字
效果:如果超过三位,比如1234567,则会返回1,234,567
*/

4、二维数组去重

function unique1(arr) {
    var obj = {};
    for (var i = 0; i < arr.length; i++) {
        // 判断当前项是否遍历过,是则删除,否存入obj以作对照
        if (obj.hasOwnProperty(arr[i])) {
            arr.splice(i, 1)
        } else {
            obj[arr[i]] = i;
        }
    }
    return arr
}

/*
参数:arr->待处理的二维数组
效果:将二维数组去重
*/

 

posted @ 2019-09-16 14:31  jee-cai  阅读(86)  评论(0编辑  收藏  举报