javascript JSLint, else 和 Expected '}' 和 'else' 之间正好有一个空格错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8130134/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 02:24:01  来源:igfitidea点击:

JSLint, else and Expected exactly one space between '}' and 'else' error

javascriptcode-formattingjslint

提问by Grzegorz Gierlik

Why JSLintreport in code:

为什么JSLint在代码中报告:

function cos(a) {
    var b = 0;
    if (a) {
        b = 1;
    }
    else {
        b = 2;
    }

    return b;
}

error:

错误:

Problem at line 6 character 5: Expected exactly one space between '}' and 'else'.

This error can be turned off by disabling Tolerate messy white spaceoption of JSLint.

可以通过禁用JSLint 的 Tolerate messy white space选项来关闭此错误。

Or in other words -- why syntax: } else {is better then

或者换句话说——为什么语法: } else {那么好

...
}
else {
...

Google also usessyntax with } else {form.

谷歌还使用} else {形式的语法。

But I don't understand why. Google mentioned ''implicit semicolon insertion'', but in context of opening {, not closing one.

但我不明白为什么。谷歌提到了“隐式分号插入”,但在打开{而不是关闭的上下文中。

Can Javascript insert semicolon after closing }of ifblock even if next token is elseinstruction?

收盘后,也可以javascript插入分号}if,即使下一个标记是块else指令?

Sorry that my question is a bit chaotic -- I tried to think loud.

抱歉,我的问题有点混乱——我试着大声思考

采纳答案by Dave Newton

JSLint is based on Crockford's preferences (which I share in this case).

JSLint 基于 Crockford 的偏好(我在这种情况下分享)。

It's a matter of opinion which is "better".

这是一个“更好”的意见问题。

(Although clearly his opinion is right ;)

(虽然他的意见显然是正确的;)

回答by PhillipKregg

It's not a matter of style. It's how ECMAScript works.

这不是风格问题。这就是 ECMAScript 的工作原理。

For better or for worse, it will automatically insert semicolons at the end of statements where it feels necessary.

无论好坏,它都会自动在语句末尾插入分号。

JavaScript would interpret this:

JavaScript 会解释这个:

function someFunc {
    return
    {
        something: 'My Value'
    };
}

As this:

像这样:

function someFunc {
    return;
    {
        something: 'My Value'
    };
}

Which is certainly what you don'twant.

这当然是你想要的。

If you always put the bracket on the same line as the ifand if elsestatement, you won't run into a problem like this.

如果你总是把括号if和 andif else语句放在同一行,你就不会遇到这样的问题。

As with any coding language, the coding style chosen should be the one that minimizes potential risk the most.

与任何编码语言一样,所选择的编码风格应该是最大程度地降低潜在风险的风格。

Mozilla Developer Network also promotes same line bracketing: https://developer.mozilla.org/en-US/docs/User:GavinSharp_JS_Style_Guidelines#Brackets

Mozilla 开发者网络也提倡相同的行括号:https: //developer.mozilla.org/en-US/docs/User: GavinSharp_JS_Style_Guidelines#Brackets

回答by hugomg

JSLint is just being picky here. The guy who wrote it also baked in many stylistic suggestions in order to keep his own code more consistent.

JSLint 只是在这里挑剔。编写它的人还提出了许多风格建议,以保持他自己的代码更加一致。

As for semicolon insertion, you shouldn't need to worry here. Inserting a semicolon before the else clause would lead to a syntax error and automatic semicolon insertion only occurs in situations where the resulting code would still be syntactically valid.

至于分号插入,这里你不用担心。在 else 子句之前插入分号会导致语法错误,并且自动分号插入仅发生在结果代码在语法上仍然有效的情况下。

If you want to read more on semicolon insertion, I recommend this nice reference

如果你想阅读更多关于分号插入的内容,我推荐这个不错的参考

Basically if you insert semicolons everywhere you only need be careful about putting the argument to "return" or "throw" (or the label for "break" and "continue") on the same line.

基本上,如果你在任何地方插入分号,你只需要小心将参数“return”或“throw”(或“break”和“continue”的标签)放在同一行。

And when you accidentally forget a semicolon, the only common cases that are likely to bite you are if you start the next line with an array literal (it might parsed as the subscript operator) or a parenthsised expression (it might be parsed as a function call)

当您不小心忘记了分号时,唯一可能让您感到困扰的常见情况是,如果您以数组文字(它可能被解析为下标运算符)或带括号的表达式(它可能被解析为函数)开始下一行称呼)

Conclusion

Should you omit optional semicolons or not? The answer is a matter of personal preference, but should be made on the basis of informed choice rather than nebulous fears of unknown syntactical traps or nonexistent browser bugs. If you remember the rules given here, you are equipped to make your own choices, and to read any JavaScript easily.

If you choose to omit semicolons where possible, my advice is to insert them immediately before the opening parenthesis or square bracket in any statement that begins with one of those tokens, or any which begins with one of the arithmetic operator tokens "/", "+", or "-" if you should happen to write such a statement.

Whether you omit semicolons or not, you must remember the restricted productions (return, break, continue, throw, and the postfix increment and decrement operators), and you should feel free to use linebreaks everywhere else to improve the readability of your code.

结论

是否应该省略可选的分号?答案是个人喜好问题,但应该基于知情选择而不是对未知语法陷阱或不存在的浏览器错误的模糊恐惧。如果您记得这里给出的规则,您就可以做出自己的选择,并轻松阅读任何 JavaScript。

如果您选择在可能的情况下省略分号,我的建议是在以这些标记之一开头的任何语句或以算术运算符标记之一“/”、“ +" 或 "-" 如果您碰巧写了这样的语句。

无论是否省略分号,您都必须记住受限制的产生式(return、break、continue、throw 以及后缀自增和自减运算符),并且您应该随时在其他任何地方使用换行符来提高代码的可读性。



By the way, I personally think that the } else {version is prettier. Stop insisting in your evil ways and joins us on the light side of the force :P

顺便说一句,我个人认为} else {版本更漂亮。不要再坚持你的邪恶方式,加入我们的力量的光明面:P

回答by Jord?o

JSLint is being very picky here, just enforcing a stylethat you might not share.

JSLint 在这里非常挑剔,只是强制执行您可能不会分享的风格

Try JSHintinstead:

试试JSHint

The project originally started as an effort to make a more configurable version of JSLint—the one that doesn't enforce one particular coding style on its users [...]

该项目最初是为了制作一个更可配置的 JSLint 版本——该版本不会对其用户强制使用一种特定的编码风格 [...]

回答by StonedRanger

I have just finished reading a book titled Mastering JavaScript High Performance. I speak under correction here, but from what I can gather is that "white space" does in fact matter.

我刚刚读完了一本名为 Mastering JavaScript High Performance 的书。我在这里说得更正,但据我所知,“空白”确实很重要。

It has to do with the way the interpreter fetches the next function. By keeping white space to a minimum (i.e.) using a minifier when your code is ready for deployment, you actually speed up the process.

它与解释器获取下一个函数的方式有关。通过在您的代码准备好部署时使用缩小器将空白保持在最小(即),您实际上加快了该过程。

If the interpreter has to search through the white space to find the next statement this takes time. Perhaps you want to test this with a piece of code that runs a loop say 10,000 times with white spacein it and then the same code minified.

如果解释器必须搜索空白区域以找到下一个语句,这需要时间。也许您想用一段代码来测试它,该代码运行循环10,000 次,其中包含空格,然后将相同的代码缩小

The statement to put before the start of the loop would be console.timeand finally console.timeEndat the end of the loop. This will then tell you how many milliseconds the loop took to compute.

放在循环开始之前的语句将是console.time最后console.timeEnd在循环结束时。这将告诉您循环计算需要多少毫秒。

回答by Catto

The JSLint error/warning is suggesting to alter code to

JSLint 错误/警告建议将代码更改为

// naming convention winner? it's subjective
} else if{
    b = 2;
}

from:

从:

}
else if{
 b = 2;
}

It prevents insert semicolons;considered more standard & conventional. most people could agree a tab between the }tabelse if{

它防止插入分号;被认为更标准和传统。大多数人可以同意在 }tabelse if{

is not the most popular method. Interesting how the opening bracket {is placed (space or not) obviously both ar subjected

不是最流行的方法。有趣的是打开支架{的放置方式(空格与否)显然都受到