前端常用工具类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->待处理的二维数组
效果:将二维数组去重
*/

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值