JavaScript技巧

68 阅读1分钟
        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);
   
        // 1. 随机获取一个布尔值 
        // **Math.random()**的区间是0-0.99,用0.5在中间百分之五十的概率
        let randomBool = () => {
            return (0.5 - Math.random()) > 0;
        }
        // 2. 比较两个时间的大小
        function compareTime(a, b) {
            return a.getTime() > b.getTime()
        }

参考链接1

参考链接2

参考链接3