在 JavaScript switch 语句中假设严格比较是否安全?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6989902/
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-25 22:36:44  来源:igfitidea点击:

Is it safe to assume strict comparison in a JavaScript switch statement?

javascripttypescomparisontype-conversionswitch-statement

提问by Paul

I have a variable that can either be boolean false, or an integer (including 0). I want to put it in a switch statement like:

我有一个可以是 booleanfalse或整数(包括 0)的变量。我想把它放在一个 switch 语句中,如:

switch(my_var){
    case 0:
         // Do something
         break;
    case 1:
         // Do something else
         break;
    case false:
         // Some other code
}

In my tests in Google Chrome, it seems to work perfectly, but I'm a little nervous to use it because I'm afraid that in some browsers, if my_varis false, it might execute the first case since 0 == false.

在我在 Google Chrome 中的测试中,它似乎工作得很好,但我使用它有点紧张,因为我担心在某些浏览器中,如果my_varfalse,它可能会执行自0 == false.

I'm just wondering if there is anything official in JavaScript that says the switch statement will use strict comparison such that 0 !== false, but I can't find anything myself, and I'm not sure if this will work well in different JavaScript engines. Does anybody know if the comparison done by a switch statement is guaranteed to be strict?

我只是想知道 JavaScript 中是否有任何官方声明 switch 语句将使用严格比较0 !== false,但我自己找不到任何东西,我不确定这是否会在不同的 JavaScript 引擎中运行良好。有人知道 switch 语句所做的比较是否保证严格?

采纳答案by Federico Lebrón

Take a look at ECMA 262, section 12.11, the second algorithm, 4.c.

看看ECMA 262,第 12.11 节,第二种算法,4.c。

c. If input is equal to clauseSelector as defined by the === operator, then...

C。如果输入等于由 === 运算符定义的子句选择器,则...

回答by Halcyon

http://qfox.nl/notes/110answers your question. (This guy knows a lot about the nitty gritty of JavaScript)

http://qfox.nl/notes/110回答您的问题。(这家伙对 JavaScript 的本质了解很多)

Switches in Javascript use strict type checking (===). So you never have to worry about coercion, which prevents a few wtfjs :). If on the other hand you were counting on coercion, tough luck because you can't force it.

Javascript 中的开关使用严格的类型检查 (===)。所以你永远不必担心强制,这会阻止一些 wtfjs :)。另一方面,如果你指望强制,那么运气不好,因为你不能强迫它。

回答by ma11hew28

Yes, switch"[uses] the strict comparison, ===".

是的,switch“[使用] 严格比较,===”。

Source: switch - JavaScript | MDN

来源:switch - JavaScript | MDN