How to define an array with conditional elements?

后端 未结 10 1686
半阙折子戏
半阙折子戏 2020-12-07 14:01

how can i define conditional array elements? i want to do something like this:

const cond = true;
const myArr = [\"foo\", cond && \"bar\"];
         


        
10条回答
  •  没有蜡笔的小新
    2020-12-07 14:14

    If you really want to keep it as a one liner, you could use:

    const cond = true;
    const myArr = ["foo"].concat(cond ? ["bar"] : []);
    

提交回复
热议问题