本文介绍了JavaScript三元运算符和JSLint中的表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近收到了一篇关于JSLint的博客帖子的评论,询问JSLint为什么会抛出以下错误:

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();

生成的错误是:

显然JSLint是期待这里的任务,更像是:

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?

我在,JavaScript中没有任何明显的内容:好的部分。并且,社区分支也报告了相同的错误。

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.

任何人?

推荐答案

这是一个表达方式。这相当于写作

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.

已经(ab)用于简洁的其他短手表达

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 有一个选项 expr 。请参阅

JSHint has an option expr for this. See ticket

运行:

/*jshint
  expr: true
*/

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

将通过

这篇关于JavaScript三元运算符和JSLint中的表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 02:40