用条件三元运算符扩展

Expansion with conditional ternary operator

简单的问题:有没有办法在使用三元运算符的条件语句中使用展开式?

const a = 1, b = 2;

// Works
console.log(...[ a, b ]);

// Works
console.log(...(a ? [ a, b ] : [ 'Not found' ]));

// Doesn't work
console.log(a ? ...[ a, b ] : 'Not found');

遗憾的是,目前无法做到这一点。 spread syntax, like its name tells us, is a part of the syntax of the language and not a ‘normal’ operator that deals with expressions (à la + or typeof). The ternary operator?: 之后需要 表达式 ,所以你不能在这些地方使用语法。

你必须做,例如

condition
    ? console.log(…)
    : console.log(…)

是和否

不,因为在某些情况下不支持

是的,你需要按照它支持的方式使用它,基本上就是操纵它

例如

const a = 1, b = 2;

// Works
console.log(...[ a, b ]);

// Doesn't work
//console.log(a ? ...[ a, b ] : 'Not found');
//use this 
a ? console.log(...[a,b]) : "Not Found"

//you can have other ways too to achieve this