JavaScript 使用枚举切换大小写

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12783610/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 17:06:33  来源:igfitidea点击:

JavaScript switch case using enum

javascriptenumsswitch-statementcase

提问by Shivan Dragon

I have an "enum" declared like so:

我有一个像这样声明的“枚举”:

var PlaceType = {
        PASSABLE_TERRAIN: 1,
        IMPASSABLE_TERRAIN: 0,
        SOMEWHAT_PASSABLE_TERRAIN: 2,
        PATH: 3
    };

and a function declared like this:

和一个这样声明的函数:

setPlaceType(placeType) {
        this.clear = false;
        this.placeType = placeType;

        alert("before switch "+(PlaceType.SOMEWHAT_PASSABLE_TERRAIN==this.placeType));
        switch(this.placeType) {
        case PlaceType.PASSABLE_TERRAIN: {
            alert("Case PASSABLE");
            break;
        }
        case PlaceType.IMPASSABLE_TERRAIN: {
            alert("Case IMPASSABLE");
            break;
        }
        case PlaceType.SOMEWHAT_PASSABLE_TERRAIN: {
            alert("Case SOMEWHAT_PASSABLE");
            break;
        }
        case PlaceType.PATH: {
            alert("Case PATH");
            break;
        }
        default: {
            alert("case default");
        }
        }
    }

if I call it like this:

如果我这样称呼它:

setPlaceType(1);

I get the following alerts: "before switch true", "case default"

我收到以下警报:“在 switch true 之前”、“case default”

if I call it like this:

如果我这样称呼它:

setPlaceType(2);

I get the following alerts: "before switch false", "case default"

我收到以下警报:“before switch false”、“case default”

In other words, the function is called with the proper argument, which, when doing (what it seems to me to be) the same comparison as the switch but via "==" I get correct behavior, but the switch never matches the values to the appropriate case. Does anybody know why?

换句话说,该函数是用正确的参数调用的,当做(在我看来是)与开关相同的比较时,但通过“==”我得到了正确的行为,但开关永远不会匹配值到适当的情况。有人知道为什么吗?

采纳答案by jbabey

The comparison operator will cast both operands to strings if either operator is a string. If you pass in a string, you are comparing string == numberwhich will cast the number to a string and, in the case of passing the string '2', it will be true.

如果任一运算符是字符串,则比较运算符会将两个操作数强制转换为字符串。如果您传入一个字符串,您正在比较string == number哪个会将数字转换为字符串,并且在传递字符串的情况下'2',它将为真。

switch case comparison uses the identity operator ===and will fail if the operands are not the same type.

switch case 比较使用恒等运算符===,如果操作数的类型不同,则会失败。

long story short, make sure you are always passing a number if your cases are comparing against numbers, you can double check like this:

长话短说,如果您的案例与数字进行比较,请确保您始终传递一个数字,您可以像这样仔细检查:

setPlaceType(placeType) {
    if (typeof placeType !== 'number') {
        throw new Error('You must pass a number to setPlaceType!');
    }
    ...
}

also, you should be calling your function like this:

此外,您应该像这样调用您的函数:

setPlaceType(PlaceType.PASSABLE_TERRAIN);

otherwise there's not really any point to using the "enumeration" (i use that term loosely) object.

否则,使用“枚举”(我松散地使用该术语)对象实际上没有任何意义。

回答by jbabey

Refering to this => Switch-Case for strings in Javascript not working as expected

参考这个 => Switch-Case for Javascript 中的字符串没有按预期工作

Switchdo a ===, while ifdo a ==.

切换做一个===,而如果做一个==

Hope this help! have a nice day

希望这有帮助!祝你今天过得愉快

回答by epascarello

The matching case is determined using the === identity operator, not the == equality operator. The expressions must match without any type conversion. It would fail if you are passing in a string and not an integer.

匹配大小写是使用=== 标识运算符确定的,而不是 == 相等运算符。表达式必须匹配而不进行任何类型转换。如果您传入的是字符串而不是整数,它将失败。

setPlaceType(1);  //"Case PASSABLE"
setPlaceType("1");  //"case default"

Example running your code with the above lines: jsFiddle

使用上述行运行代码的示例:jsFiddle

So if you are saying it is failing, you are probably comparing a string to a number. Use parseInt.

所以如果你说它失败了,你可能是在比较一个字符串和一个数字。使用 parseInt。

this.placeType = parseint(placeType,10);

回答by bPratik

When you are doing the comparison using ==js is using type-coercionto cast the 2 operands to an intermediate type, string in this case, and thus compare them successfully.

当您使用==js进行比较时,type-coercion用于将 2 个操作数转换为中间类型,在本例中为字符串,从而成功比较它们。

So to get the effect to work with your switch statement, you will need to cast as such

因此,要使效果与您的 switch 语句一起使用,您需要这样转换

this.placeType = parseint(placeType);

What you also got to learn here is that it is not really an ideal practice to compare 2 values in javascript using the ==operator, instead use the ===operator which also checks for the types to be the same. So in your case,

您还需要在这里学到的是,使用==运算符比较 javascript 中的 2 个值并不是一种理想的做法,而是使用===运算符来检查类型是否相同。所以在你的情况下,

alert("before switch "+(PlaceType.SOMEWHAT_PASSABLE_TERRAIN==this.placeType));

would have failed if you would have used ===as you are comparing an intand string

如果===您在比较时使用intstring

Working demo here: http://jsfiddle.net/pratik136/ATx8c/

这里的工作演示:http: //jsfiddle.net/pratik136/ATx8c/

回答by Wei

Another way to use enum for switch case:

将枚举用于 switch case 的另一种方法:

   const PlaceType = Object.freeze({
            PASSABLE_TERRAIN: 1,
            IMPASSABLE_TERRAIN: 0,
            SOMEWHAT_PASSABLE_TERRAIN: 2,
            PATH: 3
        });

   function setPlaceType(placeType){
      return({
              0:"Case IMPASSABLE_TERRAIN",
              1:"Case PASSABLE_TERRAIN",
              2:"Case SOMEWHAT_PASSABLE_TERRAIN",
              3:"PATH"      
              }[placeType]);
     }