有用的js技巧

  <script>
        let x, test3;
        // 1. includes
        //bad
        if (x == "abc" || x == "def" || x == "ghi" || x == "jki") {
            //logic
        }

        //better
        if (["abc", "def", "ghi", "jki"].includes(x)) {
            //logic
        }

        // 2. if true... else
        // better 
        let test1 = x > 10 ? true : false;
        // or
        let test2 = x > 10;

        // 3. 假值(undefined , null , 0 , false , NaN ,empty string) 检查
        if (test3) { } else { }

        // 4. 空值合并符
        let test4 = null ?? "";// "";
        let test5 = undefined ?? "default"; // "default"

        // 5. 获取列表中的最后一项
        let arr1 = [1, 2, 3, 4, 5];
        let arr2 = arr1.slice(-1); // 5
        console.log(arr1, arr2); // [1, 2, 3, 4, 5] 5

        // 6. 比较后返回
        function checkReturn() {
            return test3 ?? callMe("test")
        }

        // 7. 可选链操作符
        let k = {
            destination: "BJ",
            monday: {
                location: "",
                budget: "200"
            }
        }

        //better
        const res1 = k?.destination?.monday?.budget?.href; //undefined

        // 8. 多个条件
        //bad
        if (test1) { callMehod() };

        //better
        test1 && callMehod();

        // React 中很有用
        `<div>{this.state.isLoading && <Loading/>}</div>`

        // 9. 开关简化
        //bad
        switch (data) {
            case 1:
                test6()
                break;
            case 2:
                test7()
                break;
            default:
                console.log("null")
        }

        //better
        let data2 = {
            1: test6,
            2: test7
        }
        data2[type] && data2[type]();

        // 10. 参数默认值
        let add = (test8 = 1, test9 = 2) => test8 + test9;

        // 11. 条件检查优化
        //better
        let types = {
            test11, test12, test13
        }
        types[test11] && types[test11]();


        // 20. 生成指定范围内的随机数
        Math.floor(Math.random * (max - min) + min);
    </script>

链接1: link1
链接2: link2

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值