JSLint and the “Expected to see a statement and in

2019-05-30 11:47发布

I have picked up the habit of wrapping all of my case statements in curly brackets from programming in C because of this but JSLint is throwing a fit. It stops validating at that point.

My question is: Is this such a bad practice in JS? Do I not have to worry about the scope issue because JS has function scope (I understand how that would be the case, I just want a good reason not to be 'consistent' on this)?

(I know that different languages call for different practices, but i am trying to be as consisten as possible across languages to help protect my sanity.)

1条回答
贼婆χ
2楼-- · 2019-05-30 12:12

Good question.

The reason that JSLint complains about this is because it is actually contrary to the language specification for the switch/case statments:

http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf

https://developer.mozilla.org/en/JavaScript/Reference/Statements/switch

The JavaScript compier will tolerate it, however JSLint is about ensuring your code adheres to a stricter and more correct subset of JavaScript. ("The Good Bits" as Douglas Crockford puts it!)

Moreover, the extra bracing is extra characters that you will have to transmit with the website. If you don't need them, why transmit them?

Referring to your above link, the same problem does not present itself in JavaScript. So, the following will work:

var x = 0;
switch(x){
    case 0:
        var y = 1;
        alert(y);
}

See it at this JSFiddle: http://jsfiddle.net/LKWwB/

Finally, regarding your sanity, I would relinquish the tenuous grip you have on it. I did years ago and am much happier for it :-)

查看更多
登录 后发表回答