How to define an array with conditional elements?

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

    There's a few different ways, but the way you're doing it won't really work for Javascript.

    The easiest solution would be to just have an if statement.

    if (myCond) arr.push(element);
    

    There's also filter, but I don't think that's what you want here at all, since you seem to be going for "Add this one thing, if this one condition is true" rather than checking everything against some condition. Although, if you want to get really freaky, you can do this (would not recommend, but it's cool that you can).

    var arr = ["a", cond && "bar"];
    arr.filter( e => e)
    

    Basically it will just filter out all the non true values.

提交回复
热议问题