Create array and push into it in one line

后端 未结 3 884
隐瞒了意图╮
隐瞒了意图╮ 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: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
    

提交回复
热议问题