简体   繁体   中英

How to simplify conditional array value addition

Here is the code:

const presets = (buildType === "___PROD___") ?
                        [   "react",
                            "es2015",
                            { "modules" : false }
                        ] : [
                            "react",
                            "es2015"
                        ];

As can be see, the values of react , es2015 are being repeated. Is it possible to not have this repetition in the ternary operator?

Best,

How about using the spread syntax ?

var standardPresets = ['react','es2015'];
const presets = cond ? [ ...standardPresets , {modules: false} ] : [ ...standardPresets ];

Does you have to use a ternary if ? Could you just .push into the array when that condition is met?

const standardPresets = ['react','es2015'];
if(cond){ standardPresets.push({modules: false}); }

Personally, I don't think the repetition is too awful as it is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM