JavaScript 三元运算符和 JSLint 中的表达式

发布于 2024-11-14 03:48:13 字数 544 浏览 5 评论 0原文

最近,我在一篇有关 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

心房敞 2024-11-21 03:48:13

这是一个表达。它相当于编写

0 === 1;

您编写的表达式会立即产生副作用,并且被认为是不好的。

一般来说,表达式是无用的语句,没有副作用。它被认为是更好的形式,简单地做

if (s === "test") {
  MyFunc();
} else {
  MyFunc2();
}

除此之外它是完全可靠的语法。我个人确实同意编写一个简洁的三元作为 if 的替代品是不好的,你最好只将它用于赋值。

其他为了简洁而被(滥用)使用的简写表达式

someCondition && doMagic(magic);
someCondition || doMagic(magic);

如果仅用作表达式,则再次被认为是不好的形式,因为使用它们只会掩盖逻辑并使代码更难维护。

JSHint 有一个选项 expr 来实现此目的。请参阅ticket

运行:

/*jshint
  expr: true
*/

var s, MyFunc, MyFunc2;
s === "test" ? MyFunc() : MyFunc2();
0 === 1;

将通过

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

if (s === "test") {
  MyFunc();
} else {
  MyFunc2();
}

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

someCondition && doMagic(magic);
someCondition || doMagic(magic);

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 ticket

Running:

/*jshint
  expr: true
*/

var s, MyFunc, MyFunc2;
s === "test" ? MyFunc() : MyFunc2();
0 === 1;

Will pass

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文