Ternary Operator in JavaScript With Multiple Expressions?

后端 未结 6 1991
再見小時候
再見小時候 2021-01-17 14:29
the_styles ? the_styles.appendTo(\'head\'); the_styles=null : the_styles = $(\'.stylesheet\').detach();

Obviously, this isn\'t valid. Notice the \"

6条回答
  •  说谎
    说谎 (楼主)
    2021-01-17 14:46

    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?

提交回复
热议问题