What a strange syntax?

后端 未结 3 1092
温柔的废话
温柔的废话 2020-11-30 13:43

I\'ve found unknown for me code construction on JQuery site. After some formatting it looks like:

function (a,c) {
    c==null && (c=a,a=null);
            


        
相关标签:
3条回答
  • 2020-11-30 14:13

    The expression uses two JavaScript features :

    • short circuit evaluation of boolean operators: in statement context, a && (b); is equivalent to if (a) (b);
    • the comma operator to group assignment expressions: in statement context, a=b,b=c; is equivalent to { a=b; b=c }

    As a result the expression is equivalent to:

    if (c == null) {
        c = a
        a = null
    }
    
    0 讨论(0)
  • 2020-11-30 14:31

    It's a trick that uses boolean short-circuit evaluation to only do the second half if the first evaluates to true. Perl has this commonly:

    <something> or die
    

    where if the first statement failed, the program ends.

    Read it as

    if (c == null) { c = a; a = null; }
    
    0 讨论(0)
  • 2020-11-30 14:34

    That's an ugly way to write

    if(c==null) {
      c = a;
      a = null;
    }
    

    This utilizes the fact, that the second part of boolean && will be executed if, and only if the first part evaluates to true.

    0 讨论(0)
提交回复
热议问题