前端开发常用的js方法

这篇文章列举了一些常用的JavaScript方法,包括比较时间的逻辑,金额格式化的函数,生成随机ID的算法,以及利用+符号转换数字和时间戳的技巧。此外,还介绍了判断奇偶数、数据类型的函数以及检查数组和对象是否为空的方法。
摘要由CSDN通过智能技术生成

 记录下经常用的的js方法:

//比较时间
        const time1 = "20223-04-20 09:00:00";
        const time2 = "2023-04-20 09:00:01";
        const overtime = time1 < time2;
        //console.log(overtime)  true

        //金额格式化
        const ThousandNum = num => num.toString().replace(/\B(?=(\d{2})+(?!\d))/g, ",");
        const money = ThousandNum(1000000);
        console.log(money)

        //生成随机id
        const RandomId = len => Math.random().toString(36).substr(3, len);
        const id = RandomId(8);
        console.log(id)  //4v6nycoc

        //+号的妙用 转化为数字或者时间戳
        const num1 = +null; //0
        const num2 = +""; //0
        const num3 = +false; //0
        const num4 = +"169";  //169
        const timestamp = +new Date("2023-04-20"); //时间戳

        //十进制数字
        const RoundNum = (num, decimal) => Math.round(num * 10 ** decimal) / 10 ** decimal;
        const num = RoundNum(1.2345, 2);
        // num => 1.23
        
        //判断奇数偶数
        const OddEven = num => !!(num & 1) ? "odd" : "even";
        const num = OddEven(2);

        //判断数据的类型
        function DataType(tgt, type) {
                const dataType = Object.prototype.toString.call(tgt).replace(/\[object (\w+)\]/, "$1").toLowerCase();
            return type ? dataType === type : dataType;
            }

            DataType("test"); // "string"
            DataType(20220314); // "number"
            DataType(true); // "boolean"
            DataType([], "array"); // true
            DataType({}, "array"); // false

        //判断数组是否为空
        const arr = [];
        const flag = Array.isArray(arr) && !arr.length;

        //判断对象不为空
        const obj = {a: 0, b: 1, c: 2};
        Object.keys(obj).length>0

        //数组转化为对象

        const arr = [0, 1, 1, 2, 2, 2];
        const count = arr.reduce((t, v) => {
            t[v] = t[v] ? ++t[v] : 1;
            return t;
        }, {});
        // count => { 0: 1, 1: 2, 2: 3 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

m0_45925246

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值