How to define an array with conditional elements?

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

    if you are using es6, I would suggest

    let array = [ "bike", "car", name === "van" ? "van" : null, "bus", "truck", ].filter(Boolean);

    This array will only contain value "van" if name equals "van", otherwise it will be discarded.

提交回复
热议问题