使用条件元素定义JavaScript数组文字

Jel*_*tor 1 javascript arrays

我想使用包含元素的文字来创建JavaScript数组。如果某个表达式为真,我只希望包含这些元素的一部分(在数组中间的某个位置)。我显然可以使用始终存在的元素创建数组,然后在条件为真的情况下以编程方式在适当的索引处插入其他元素,但是我不想这样做,因为非ES6的处理方式不是很如果条件为真(不是很易读),那么您就必须认真思考索引,以了解条件元素将要去往何处。这是我知道该怎么做(但不喜欢)与我想做什么(但不知道怎么做)的简化示例。在最后一个示例中,undefined在索引中,我根本不希望有元素。有没有一种方法可以通过文字和表达式来实现,或者我将不得不做一些数组操作来实现这一点?

function createArrayTheWayIDislike(condition) {
    var array = [
        'a',
        'd'
    ];
    if(condition) {
       array.splice.apply(array, [1, 0].concat(['b', 'c']));
    }
    console.log(array);
}

function createArrayTheWayIWantTo(condition) {
    var array = [
        'a',
        condition ? 'b' : undefined,
        condition ? 'c' : undefined,
        'd'
    ];
    console.log(array);
}

createArrayTheWayIDislike(true);
createArrayTheWayIDislike(false);

createArrayTheWayIWantTo(true);
createArrayTheWayIWantTo(false);
Run Code Online (Sandbox Code Playgroud)

Ren*_*ama 5

您可以在返回数组之前过滤结果

function createArrayTheWayIWantTo(condition) {
    var array = [
        'a',
        condition ? 'b' : undefined,
        condition ? 'c' : undefined,
        'd'
    ].filter(e => e);
    
    console.log(array);
}

createArrayTheWayIWantTo(true);
createArrayTheWayIWantTo(false);
Run Code Online (Sandbox Code Playgroud)