zoukankan      html  css  js  c++  java
  • javascript中对条件推断语句的优化

    无论写什么程序,平时都会用到条件语句,如:if...else... switch这种语句,来达到对条件的推断。

    以下看来一段代码:

    function abc(test){
        if (test == 1){
            console.log('test的值是'+test);
        }
        else if (test == 2){
            console.log('test的值是'+test);
        }
        else if (test == 3){
            console.log('test的值是'+test);
        }
        else if (test == 4){
            console.log('test的值是'+test);
        }
    }
    
    abc(1);
    abc(2);
    abc(3);
    abc(4);

    结果例如以下:

    test的值是1
    test的值是2
    test的值是3
    test的值是4
    [Finished in 0.1s]

    事实上在平时的代码开发中这并没有什么问题,可是非常多的时候我们都希望自己的代码可以变的优雅和简单易懂,而且尽可能少的降低反复的代码。对于以上的问题,在js中存在一个switch来取代这种多if语句推断。

    优化后的代码例如以下:

    function bcd(test){
        switch(test){
            case 1:
                console.log('test的值是'+test);
                break;
            case 2:
                console.log('test的值是'+test);
                break;
            default:
                console.log('test的值是null');
        }
    }
    
    bcd();
    bcd(1);

    结果例如以下:

    test的值是null
    test的值是1

    那么在js中有没有更好的方法来做到呢?使用js对象的特点可以轻松对switch进行优化。代码例如以下:

    function dcf(test){
        return({
                cat :function(){console.log('cat');},
                dog :function(){console.log('dog');},
                zhiqiang : function(){console.log('zhiqiang');}
            }[test] || function(){console.log('我是默认值');}
        )();
    }
    
    dcf();
    dcf('dog');

    我是默认值
    dog

    这里主要作用到两个知识点:1.js获取对象属性的值2.||操作符取值的问题。

  • 相关阅读:
    Best Time to Buy and Sell Stock
    Remove Nth Node From End of List
    Unique Paths
    Swap Nodes in Pairs
    Convert Sorted Array to Binary Search Tree
    Populating Next Right Pointers in Each Node
    Maximum Subarray
    Climbing Stairs
    Unique Binary Search Trees
    Remove Duplicates from Sorted Array
  • 原文地址:https://www.cnblogs.com/mfrbuaa/p/5225415.html
Copyright © 2011-2022 走看看