简体   繁体   English

反向切换语句是否可以接受JavaScript?

[英]Is a reversed switch statement acceptable JavaScript?

JSLint is complaining that (true) is a weird condition . JSLint抱怨说(true)是一种weird condition Which is understandable if I wasn't using it on a reversed switch statement. 如果我没有在反向切换声明中使用它,这是可以理解的。 So is JSLint wrong or should I not be using reversed switch statements? 那么JSLint是错误的还是我不应该使用反向切换语句?

Thanks for any help/enlightenment. 感谢您的帮助/启发。

switch (true) {
    case (menuLinksLength < 4):
        numberOfColumns = 1;
        break;
    case (menuLinksLength > 3 && menuLinksLength < 7):
        numberOfColumns = 2;
        break;
    case (menuLinksLength > 6 && menuLinksLength < 10):
        numberOfColumns = 3;
        break;
    case (menuLinksLength > 9):
        numberOfColumns = 4;
        break;
    default:
        numberOfColumns = 0;
}

Personally I wouldn't like seeing reversed switch in a code base. 我个人不喜欢在代码库中看到反向switch It doesn't buy you anything when compared to a plain if/elseif block, and its exotic nature can be cause for confusion. 与普通的if/elseif块相比,它不会给你任何东西,它的异国情调可能会导致混乱。

That's also what JSLint is complaining about: 这也是JSLint抱怨的内容:

You are doing something unorthodox. 你正在做一些非正统的事情。 Is there a good reason for it? 它有充分的理由吗? If not, it might be better to stick to the basics. 如果没有,坚持基础可能会更好。

The third edition of the ECMA-262 standard (supported by Firefox 1.0+, Google Chrome 1.0+, MSIE 5.5+ and others) defines that ECMA-262标准的第三版(由Firefox 1.0 +,Google Chrome 1.0 +,MSIE 5.5+和其他人支持)定义了

switch (expression) {
    case label1:
        statements1
    .
    .
    .
}

executes statements1 if (expression) matches label1 . 如果(expression)匹配label1则执行statements1

That means that your switch statement is perfectly fine. 这意味着你的switch语句非常好。

I tried it out on Firefox, Chrome and IE. 我在Firefox,Chrome和IE上尝试过。 None complains... 无抱怨......

Edit: 编辑:

Now the guessing part: 现在猜测部分:

JSLint is a code anaylisis tool. JSLint是一个代码anaylisis工具。 When it sees switch (true) , it assumes that you don't know what you're doing. 当它看到switch (true) ,它假定你不知道你在做什么。 Weird doesn't mean necessarily wrong ... 奇怪并不一定意味着 ......

numberOfColumns = Math.max(4, Math.floor(menuLinksLength / 3));

This will give you identical results to your existing code. 这将为您提供与现有代码相同的结果。 Your question is fairly ambiguous, as "acceptable" is a very subjective term. 你的问题很模糊,因为“可接受的”是一个非常主观的术语。 I would personally reject any merge request with a reversed switch statement, because I actually can't think of a situation where that couldn't be replaced with something simpler and/or easier to read. 我个人会拒绝任何带有反向切换语句的合并请求,因为我实际上无法想到一个不能用更简单和/或更容易阅读的东西替换的情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM