且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将此if语句转换为switch语句?

更新时间:2021-09-13 04:36:45

Manas Kumar是对的。我们根本不需要考虑您的开关,错误与否。此外,硬编码5可能是坏的:你没有重复使用常量,因此可能无法支持代码。



但是还有一个问题,更深层次的问题。条件 i === 5 表示您不确定 i 是否为数字。但是您使用上面的条件 i< = 5 ,这表明 i 应该已经被测试为数字,事实并非如此。您必须在数字比较之前执行'==='检查。这是不考虑你的开关代码片段的另一个原因。只有在您的原始代码正确且知道它实现了什么的情况下,修改代码才能有意义。由于我描述的问题,情况并非如此。如果这个===条件有意义,则不应使用开关



身份(严格相等)运算符'===',而不是等于运算符'==',例如,这里解释:比较运算符 - JavaScript | MDN [ ^ ]。



绝对的初学者(正如你所说)使用JavaScript的做法很有趣,而且......有问题。这种语言很乐意使用;从概念上讲,它非常简单和优雅,是世界上最容易被误解的语言:

JavaScript:世界上最容易被误解的编程语言 [ ^ ],

Douglas Crockford撰写的世界上最容易被误解的编程语言 - 你好! 2013 | Eventer [ ^ ]。



-SA
Manas Kumar is right. We simply don't need to consider your switch, wrong or not. Besides, hard-coding "5" might be bad: you are not reusing the constant and, hence, can have trouble supporting the code.

But there is one more problem, a deeper one. The condition i === 5 suggests that you are not sure that i is numeric. But you are using the condition i <= 5 above, which suggests that i should already be tested as numeric, which is not the case. You have to do the '===' check before numerical comparison. And this is another reason for not considering your switch piece of code. Review of modified code could make sense only if your original code is correct, and if it's known what it achieves. Due to the problem I described, this is not the case. If this '===' condition makes sense at all, switch should not be used.

The identity (strict equality) operator '===', as opposed to equality operator '==', is explained, for example, here: Comparison operators — JavaScript | MDN[^].

The practice of using JavaScript by "absolute beginners" (as you said) is interesting and, well… questionable. This language is pleasure to use; being very simple and elegant, it is, conceptually, quite tricky and unusual, is the world's most misunderstood language:
JavaScript: The World's Most Misunderstood Programming Language[^],
The World's Most Misunderstood Programming Language by Douglas Crockford — YOW! 2013 | Eventer[^].

—SA

>