简体   繁体   English

具有多个表达式的JavaScript中的三元运算符?

[英]Ternary Operator in JavaScript With Multiple Expressions?

the_styles ? the_styles.appendTo('head'); the_styles=null : the_styles = $('.stylesheet').detach();

Obviously, this isn't valid. 显然,这是无效的。 Notice the ";" 注意“;” between the appendTo() and the_styles=null . appendTo()the_styles=null How do I write it on 1 line and still have multiple expressions like that? 我如何在1行上写它仍然有这样的多个表达式?

Use the comma operator this way: 以这种方式使用逗号运算符:

the_styles ? (the_styles.appendTo('head'), the_styles=null) : the_styles =  $('.stylesheet').detach();

Here's what the Mozilla Developer Center writes about the comma operator: 以下是Mozilla开发人员中心撰写的有关逗号运算符的内容:

You can use the comma operator when you want to include multiple expressions in a location that requires a single expression. 如果要在需要单个表达式的位置包含多个表达式,可以使用逗号运算符。 The most common usage of this operator is to supply multiple parameters in a for loop. 此运算符的最常见用法是在for循环中提供多个参数。

Read more here: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/Comma_Operator 在此处阅读更多内容: https//developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/Comma_Operator

Who needs the ternary operator? 谁需要三元运算符?

​the_styles = !the_styles && $('.stylesheet').detach()​​​​ ||
             the_styles.appendTo('head') && null;​

Had to switch the expressions around as otherwise the null value of the first expression will always force the second expression .detach() to be evaluated. 必须切换表达式,否则第一个表达式的null值将始终强制计算第二个表达式.detach()

The only thing about clever code is that once you come back to it after a coffee break, it won't make any sense even to you. 巧妙的代码唯一的问题是,一旦你喝完咖啡休息后回到它,它对你来说也没有任何意义。 So this is much better: 所以这更好:

if(the_styles) {
    the_styles.appendTo('head')
    the_styles = null;
}
else {
    the_styles = the_styles.detach('.stylesheet');
}

To me, even the above simplistic version doesn't make any sense. 对我来说,即使是上面简单的版本也没有任何意义。 The what part is obvious, but why is it doing that? 什么部分是显而易见的,但为什么这样做呢?

the_styles ? (function() {the_styles.appendTo('head'); the_styles=null})() : <etc>

Just wrap the code block in (function() { and })() . 只需将代码块包装在(function() {})()

Now for the hard part: why would you want to do this? 现在是困难的部分:你为什么要这样做? Perhaps there's a better solution! 也许有更好的解决方案!

我同意glowcoder,但如果你仍然想要它:

the_styles ? function(){ the_styles.appendTo('head'); the_styles=null;}() : the_styles = $('.stylesheet').detach();
the_styles ? the_styles.appendTo('head') : the_styles = $('.stylesheet').detach();

如果你覆盖它,你不需要取消它!

the_styles=the_styles || $('.stylesheet').detach(); the_styles.appendTo('head');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM