Add elements inside Array conditionally in JavaScript

后端 未结 3 635
日久生厌
日久生厌 2020-12-08 13:37

When I try to merge two objects using the spread operator conditionally, it works when the condition is true or false:

let conditio         


        
3条回答
  •  清歌不尽
    2020-12-08 13:54

    false is not spreadable.

    You need a spreadable object (the one where Symbol.iterator is implemented) which returns nothing, if spreaded.

    You could use an empty array as default value. This works even if arr is falsy.

    let condition = false;
    let arr1 = ['value1'];
    let arr2 = ['value2', ...(condition && arr || [])];
    
    console.log(arr2);

提交回复
热议问题