How to define an array with conditional elements?

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

    You don't have so many options other than using push:

    const cond = true;
    const myArr = ["foo"];
    
    if (cond) myArr.push("bar");
    

    Another idea is potentially adding null's and filtering them out:

    const cond = true;
    const myArr = ["foo", cond ? "bar" : null];
    
    myArr = myArr.filter((item) => item !== null);
    

提交回复
热议问题