How to define an array with conditional elements?

后端 未结 10 1661
半阙折子戏
半阙折子戏 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);
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-07 14:29

    You can try with a simple if :

    if(cond) {
        myArr.push("bar");
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题