在 Javascript 中,可以将三元运算符的 `?` 放在下一行吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7259065/
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-25 23:29:15  来源:igfitidea点击:

In Javascript, is it OK to put the ternary operator's `?` on then next line?

javascriptjshint

提问by hugomg

I really like aligning the ? and the : of my ternary operator when they don't fit on a line, like this:

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

var myVar = (condition
    ? ifTrue
    : ifFalse
);

However, JSHintcomplains with:

但是,JSHint抱怨:

Bad line breaking before '?'

'?' 之前断行错误

Why would JSHint have this warning? Is there any nastyness (like semicolon insertion, etc) it is protecting me against or can I safely change my JSHINT configuration to ignore it?

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

采纳答案by pimvdb

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;

回答by Mrchief

UPDATE: This answer is outdated now. Apparently Crockford changes his mind ;)

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

See @CheapSteaks's answerfor the update.

请参阅@CheapSteaks对更新的回答

Per Crockford:

Place the break after an operator, ideally after a comma. A break after an operator decreases the likelihood that a copy-paste error will be masked by semicolon insertion.

So:

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

If you run this sample code through JSHint, this will pass:

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

克罗克福德

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

所以:

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

如果您通过 JSHint 运行此示例代码,它将通过:

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

回答by CheapSteaks

Per Crockford

克罗克福德

The ternary operator can be visually confusing, so ? question mark always begins a line and increase the indentation by 4 spaces, and : colon always begins a line, aligned with the ? question mark. The condition should be wrapped in parens.

三元运算符可能在视觉上令人困惑,所以 ? 问号总是以一行开头并增加 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;
};

回答by Daniel A. White

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

您应该将操作符放在行尾。这样更清楚的是,语句继续到下一行。