使用object literal替换switch

提问:

1.为什么要使用switch方法  ==> (替换冗长的if和else判断)

2.什么场景下使用 ==> (在判断布尔值的)

3.switch有什么优点 ==> (简化了代码,语法更清晰)

4.switch有什么缺点 ==> (太多的case和break关键字,出现bug时难于调试)

5.还有什么更好的替换方法吗  ==> (使用对象字面量)

6.object literal有什么优点 ==> (可扩展性,可维护性,和更好的调试);

1.switch语法(替换冗长的if和else判断)

(function(){
    var type = "coke";
    var drink;
    switch(type){
        case "coke" :
            drink = "coke";
            break;
        case "pepsi":
            drink = "pepsi";
            break;
        default :
            drink = "unknown drink"
    }
    console.log(drink);
}());

2.if和else做太多判断,语句太冗长

(function(){
    var type = "coke";
    if(type === "coke"){
        type = "coke";
    }else if(type === "pepsi"){
        type = "pepsi";
    }else{
        type = "Unknown drink";
    }
}());

3.使用对象字面量

(function(){
    function getDrink(type){
        var drinks = {
            "coke" : "Coke",
            "pepsi" : "Pepsi",
            "lemoande" : "Lemonade",
            "default" : "Default item"
        };
        return "The drink i chose was " + (drinks[type] || drinks["default"]);
    }
    var drink = getDrink("pepsi");      //有选择参数
    var drink2 = getDrink();            //默认
    console.log(drink);
    console.log(drink2);
}());

4.返回函数调用

(function(){
    var type = "coke";
    var drinks = {
        coke : function(){
            return "Coke";
        },
        pepsi : function(){
            return "Pepsi";
        },
        lemoande : function(){
            return "Lemoande";
        }
    }
    console.log(drinks[type]());
}());

5.返回有“默认值”函数调用

(function(){
    function getDrink(type){
        var fn;
        var drinks = {
            coke : function(){
                return "Coke";
            },
            pepsi : function(){
                return "Pepsi";
            },
            lemoande : function(){
                return "Lemoande";
            },
            default : function(){
                return "Default item";
            }
        };
        if(drinks[type]){
            fn = drinks[type];
        }else{
            fn = drinks["default"];
        }
        return fn();
    }
    var drink = getDrink("lemoande");
    var drink2 = getDrink();
    console.log(drink);     //Lemoande
    console.log(drink2);    //Default item
}());

6.使用||表达式来返回“默认值”函数调用

(function(){
    function getDrink(type){
        var drinks = {
            coke : function(){
                return "Coke";
            },
            pepsi : function(){
                return "Pepsi";
            },
            lemoande : function(){
                return "Lemoande";
            },
            default : function(){
                return "Default item";
            }
        };
        return (drinks[type] || drinks["default"])();
    }
    var drink = getDrink("lemoande");
    var drink2 = getDrink();
    console.log(drink);     //Lemoande
    console.log(drink2);    //Default item
}());

7.有其他返回值的时候

(function(){
    function getDrink(type){
        var item;
        var drinks = {
            coke : function(){
                item = "Coke";
            },
            pepsi : function(){
                item = "Pepsi";
            },
            lemoande : function(){
                item = "Lemoande";
            },
            default : function(){
                item = "Default item";
            }
        };

        //invoke it
        (drinks[type] || drinks["default"])();

        //return something
        return ‘The drink I chose was ‘ + item;
    }

    var drink = getDrink("lemoande");
    var drink2 = getDrink();
    console.log(drink);     //Lemoande
    console.log(drink2);    //Default item
}());

8.当有多个case同一个条件的switch

(function(){
    var type = "coke";
    var snack;
    switch(type){
        case "coke" :
        case "pepsi" :
            snack = "Drink";
            break;
        case "cookies" :
        case "crisps" :
            snack = "Food";
            break;
        default :
            snack = "Unknown type!";
    }
    console.log(snack);
}());

9.使用对象直接量替换switch

(function(){
    function getSnack(type){
        var snack;
        function isDrink(){
            return snack = "Drink";
        }
        function isFood(){
            return snack = "Food";
        }
        var snacks = {
            "coke" : isDrink,
            "pepsi" : isDrink,
            "cookies" : isFood,
            "crisps" : isFood
        };
        return snacks[type]();
    }
    var drink = getSnack("coke");
    console.log(drink);
}());

10.总结

1.switch有太多case和break关键字,且太散乱,出现bug时难于调试。

2.对象字面量有更多的可扩展性,可维护性,和更好的调试,可以包含函数和任何其他对象类型,非常有灵活性,且可以产生闭包,返回闭包。

PS:原文参考:https://toddmotto.com/deprecating-the-switch-statement-for-object-literals/

时间: 2024-08-06 03:40:17

使用object literal替换switch的相关文章

C#中一种替换switch语句更优雅的写法

今天在项目中遇到了使用switch语句判断条件,但问题是条件比较多,大概有几十个条件,满屏幕的case判断,是否有更优雅的写法替代switch语句呢? 假设有这样的一个场景:商场经常会根据情况采取不同的打折方案,如果打折方案比较少,可以考虑使用switch语句作判断.但如果有几十甚至几百种打折方案的时候,用switch语句就不够优雅. 先来一个打折接口. public interface IValueProcessor { decimal DaZhe(short policy,decimal o

object literal对象字面量

<JavaScript高级程序设计(第3版)>有个陌生的新词:对象字面量,无法理解.看了一下英文原版,英文是object literal ,还是不太理解.后来想明白了,主要是literal 这个词不好理解.它是什么意思呢?我们说话时,有时会使用比喻或隐喻,比如我们说雄鹰展翅飞,一般指的不是天上有只鹰在飞,一般是形容一个人胸怀大志,而如果用了literal ,它的意思就是,就是字面上的意思,没有比喻.比如,还是说雄座展翅飞,我并不是在描述某个人像雄鹰一样自由飞翔,而是天上真的有一只雄鹰在飞,这就

word 文档操作类,可以读出word中书签 批量替换内容,直接调用

using System;using System.Collections.Generic;using System.Text;using Word = Microsoft.Office.Interop.Word; namespace ELO.BLL{ /* * Description:用于Word基本操作类 */public partial class Helper_Word { #region 私有成员 private Word.ApplicationClass _wordApplicati

var, function, object, parameter怎么理解?

var是用来存放data value的(container).data type包括number, string, array, math, date等(其中string, array, math, date都是object). function是a block of code,优势:通过不同的arguments(和parameters一个意思)来实现code reuse. object是用来存放多个values,并以name: value/property: property value出现:

Object.create(): the New Way to Create Objects in JavaScript

There are a lot of ways to create Objects in JavaScript, perhaps even more to integrate inheritance into them. Just when you thought that you've seen every possible way to create JS objects, I'm here to announce that there's yet another: the new Obje

JavaScript基础Literal 与 Constructor(008)

JavaScript支持以字面声名法(Literal)的方式来声名对象和数组,相对于构造函数(constructor)的方式,Literal的声 名方式更简洁,更易读,也更少导致Bug.事实上,JSON就是用Literal的方式定义的JavaScript数据格式. 1. 用Literal的方式创建对象JavaScript里的对象大概就好像是一个装着一堆“键-值对”的哈希表.下面我们给出以Literal方式声名对象的语法: 用花括号把对象的内部包起来(即{}): 对象中的各个键值对之间要用逗号分开

Object Creation

Although using the object constructor or an object literal are convenient ways to create single objects, there is an obvious downside: creating multiple objects with the same interface requires a lot of code duplication. To solve this problem, develo

ECMAScript6 Object

二.对象 A lot of ECMAScript 6 focused on improving the utility of objects. The focus makes sense given that nearly every value in JavaScript is represented by some type of object. Additionally, the number of objects used in an average JavaScript program

成为C++高手之if与switch

计算器第三版 上一节中的这一部分: //跟据运算符进行不同的运算 if(opt == 1){ //加 result = number1+number2; } if(opt == 2){ //减 result = number1-number2; } if(opt == 3){ //乘 result = number1*number2; } if(opt == 4){ //除,现在只能整除 result = number1/number2; } 有点问题,虽然逻辑上没问题,但是运行不高效.因为如果