Is a reversed switch statement acceptable JavaScript?

后端 未结 3 857
无人共我
无人共我 2020-12-20 19:12

JSLint is complaining that (true) is a weird condition. Which is understandable if I wasn\'t using it on a reversed switch statement. So is JSLint

相关标签:
3条回答
  • 2020-12-20 19:30
    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.

    0 讨论(0)
  • 2020-12-20 19:35

    The third edition of the ECMA-262 standard (supported by Firefox 1.0+, Google Chrome 1.0+, MSIE 5.5+ and others) defines that

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

    executes statements1 if (expression) matches label1.

    That means that your switch statement is perfectly fine.

    I tried it out on Firefox, Chrome and IE. None complains...

    Edit:

    Now the guessing part:

    JSLint is a code anaylisis tool. When it sees switch (true), it assumes that you don't know what you're doing. Weird doesn't mean necessarily wrong...

    0 讨论(0)
  • 2020-12-20 19:39

    Personally I wouldn't like seeing reversed switch in a code base. It doesn't buy you anything when compared to a plain if/elseif block, and its exotic nature can be cause for confusion.

    That's also what JSLint is complaining about:

    You are doing something unorthodox. Is there a good reason for it? If not, it might be better to stick to the basics.

    0 讨论(0)
提交回复
热议问题