在 JavaScript switch 语句中假设严格比较是否安全? [英] Is it safe to assume strict comparison in a JavaScript switch statement?

查看:29
本文介绍了在 JavaScript switch 语句中假设严格比较是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个变量,它可以是布尔值 false 或整数(包括 0).我想把它放在一个 switch 语句中,如:

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:

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

在我在 Google Chrome 中的测试中,它似乎运行良好,但我使用它有点紧张,因为我担心在某些浏览器中,如果 my_varfalse,它可能会执行第一种情况,因为 0 == false.

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_var is false, it might execute the first case since 0 == false.

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

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?

推荐答案

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

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

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

这篇关于在 JavaScript switch 语句中假设严格比较是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆