How to define an array with conditional elements?

后端 未结 10 1676
半阙折子戏
半阙折子戏 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:06

    const cond = false;
    const myArr = ["foo", cond ? "bar" : null].filter(Boolean);
    
    console.log(myArr)
    

    Will result in ["foo"]

提交回复
热议问题