Ternary Operator in JavaScript With Multiple Expressions?

一个人想着一个人 提交于 2019-12-04 02:57:49

问题


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. 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:

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.

Read more here: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/Comma_Operator




回答2:


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.

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?




回答3:


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

Just wrap the code block in (function() { and })().

Now for the hard part: why would you want to do this? Perhaps there's a better solution!




回答4:


i agree with glowcoder but if you still want it:

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



回答5:


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

you dont need to null it if your overwriting it !




回答6:


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


来源:https://stackoverflow.com/questions/3168136/ternary-operator-in-javascript-with-multiple-expressions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!