37

我真的很喜欢对齐?以及我的三元运算符的 : 当它们不适合一行时,如下所示:

var myVar = (condition
    ? ifTrue
    : ifFalse
);

然而,JSHint抱怨:

'?' 之前的坏换行符

为什么 JSHint 会有这个警告?是否有任何讨厌的东西(如分号插入等)可以保护我,或者我可以安全地更改我的 JSHINT 配置以忽略它吗?

4

4 回答 4

28

This works and is certainly valid. It's especially useful in more complicated use cases, like nested ones.

var a = test1
         ? b
         : test2
            ? c
            : d;
于 2011-08-31T15:09:12.770 回答
26

更新:这个答案现在已经过时了。显然,克罗克福德改变了主意;)

请参阅@CheapSteaks 的更新答案

克罗克福德

将中断放在运算符之后,最好是在逗号之后。运算符后的中断降低了复制粘贴错误被分号插入掩盖的可能性。

所以:

// this is ok
var myVar = (condition ?
    ifTrue : 
    ifFalse
);

如果您通过 JSHint 运行此示例代码,则会通过:

// this is ok
var myVar = (1==1 ?
    true : 
    false
);

于 2011-08-31T15:12:21.227 回答
18

克罗克福德

三元运算符在视觉上可能会令人困惑,所以 ? 问号总是开始一行并将缩进增加4个空格,并且:冒号总是开始一行,与?对齐 问号。条件应该用括号括起来。

var integer = function (
    value,
    default_value
) {
    value = resolve(value);
    return (typeof value === "number")
        ? Math.floor(value)
        : (typeof value === "string")
            ? value.charCodeAt(0)
            : default_value;
};
于 2017-03-17T15:29:13.400 回答
6

You should put the operator on the end of the line. That way its more clear that the statment continued to the next line.

于 2011-08-31T15:07:44.907 回答