我在chrome控制台中写了这个表达式:
true || undefined ? undefined : false;然后它返回:
undefined怎么回事?

发布于 2021-04-04 22:49:27
条件(true || undefined)为true,因此ternary operator将采用undefined作为结果:
const condition = true || undefined;
console.log("condition:", condition);
console.log("result:", condition ? undefined : false);
如果您的目标是按||拆分
const result = true || (undefined ? undefined : false);
console.log("result:", result);
发布于 2021-04-04 22:49:46
||比?:具有更高的优先级,这使得表达式等同于(true || undefined) ? undefined : false;。因此,它首先计算true || undefined,它的计算结果为true,然后选择:的真实方面,即undefined。
发布于 2021-04-04 22:50:35
该表达式等同于:
if (true) {
return undefined;
} else if (undefined) {
return undefined;
} else {
return false;
}所以它返回第一个undefined。
https://stackoverflow.com/questions/66942446
复制相似问题