Create array and push into it in one line

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

提交回复
热议问题