JavaScript 三元运算符和 JSLint 中的表达式
最近,我在一篇有关 JSLint 的博客文章中收到一条评论,询问为什么 JSLint 会抛出以下错误:
s === "test" ? MyFunc() : MyFunc2();
生成的错误是:
“期望分配或功能 打电话,却看到了一个表情。”
显然,JSLint 期望在这里进行赋值,更像是:
var y = (s === "test") ? MyFunc() : MyFunc2();
的问题。三元运算符真的应该只用于赋值吗?
我在 JSLint.com 上看不到任何内容,JavaScript 书中也没有任何明显的内容:好的部分。并且,社区分支 JSHint 中也报告了相同的错误
。
I recently received a comment on one of my blog posts about JSLint asking why JSLint threw an error with the following:
s === "test" ? MyFunc() : MyFunc2();
The error generated was:
"Expected an assignment or function
call and instead saw an expression."
Clearly JSLint is expecting an assignment here, somthing more like:
var y = (s === "test") ? MyFunc() : MyFunc2();
But, I don't really see the problem with the first example. Is it really the case that ternary operators should only be used for assignments?
I couldn't see anything on JSLint.com, nor was there anything apparent in the book JavaScript: The Good Parts. And, the same error is also reported in the community fork JSHint.
Anyone?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是一个表达。它相当于编写
0 === 1;
您编写的表达式会立即产生副作用,并且被认为是不好的。
一般来说,表达式是无用的语句,没有副作用。它被认为是更好的形式,简单地做
除此之外它是完全可靠的语法。我个人确实同意编写一个简洁的三元作为
if
的替代品是不好的,你最好只将它用于赋值。其他为了简洁而被(滥用)使用的简写表达式
如果仅用作表达式,则再次被认为是不好的形式,因为使用它们只会掩盖逻辑并使代码更难维护。
JSHint 有一个选项
expr
来实现此目的。请参阅ticket运行:
将通过
It's an expression. It's equivalent to writing
0 === 1;
You're writing an expression that has immediate side effects and that's considered bad.
Generally expressions are useless statements that have no side effect. It's considered better form to simply do
Apart from that it's perfectly solid syntax. I personally do agree that writing a terse ternary as an alternative to an
if
is bad and you're better off only using it for assignment.Other short hand expression that have been (ab)used for terse-ness
Again these are considered bad form if there used only as expressions because using these just obscures logic away and make it harder to maintain code.
JSHint has an option
expr
for this. See ticketRunning:
Will pass