Create array and push into it in one line

后端 未结 3 882
隐瞒了意图╮
隐瞒了意图╮ 2021-02-04 23:47

The following is just a theoretical JavaScript question. I am curious if the following can be converting into a single statement:

if(!window.foo){
  window.foo =         


        
相关标签:
3条回答
  • 2021-02-05 00:22

    Your code works just fine if you add parentheses so that it does what you intended:

    (window.foo || (window.foo = [])).push('bar');
    

    Without the parentheses, it thinks that it should evaluate window.foo || window.foo first, and then assign the array to the result of that, which is not possible.

    0 讨论(0)
  • You've got your assignment backwards*. It should be:

    (window.foo = window.foo || []).push('bar');
    

    The || operator in JavaScript does not return a boolean value. If the left hand side is truthy, it returns the left hand side, otherwise it returns the right hand side.

    a = a || [];
    

    is equivalent to

    a = a ? a : [];
    

    So an alternative way of writing the above is:

    (window.foo = window.foo ? window.foo : []).push('bar');
    

    * see comments for details

    0 讨论(0)
  • 2021-02-05 00:40

    This question got me playing with different options for fun. It's too bad push returns the length instead of the original array reference, but for even shorter expressions it can be helpful to have something that can be immediately iterated, mapped, etc.

    window.foo = (window.foo||[]).concat(['bar']); // always returns array, allowing:
    (window.foo = (window.foo||[]).concat(['bar'])).forEach( ... )
    
    (window.foo = window.foo||[]).push('bar'); // always returns length
    
    window.foo && window.foo.push('bar') || (window.foo = ['bar']); // playing around
    
    0 讨论(0)
提交回复
热议问题