【发布时间】:2020-07-27 11:50:01
【问题描述】:
通过OR 合并一个字符串(通过PRIORITIES[NUM_TO_PRIORITY[priorityNum]],其中priorityNum 是输入)和一个字符串(通过条件Object.values(PRIORITIES).includes(priorityNum) ? priorityNum : PRIORITIES.low)进行空值合并应该输出一个字符串但输出一个数字(与输入匹配)。为什么会这样?
这可能是一个 js 怪癖,但不确定为什么输出是一个数字,因为测试表明合并应该在 2 个字符串之间以输出一个字符串:
const PRIORITIES = {
high: 'HIGH',
low: 'LOW',
};
const NUM_TO_PRIORITY = {
0: 'high',
1: 'low',
};
const priorityNum = 0;
console.log(PRIORITIES[NUM_TO_PRIORITY[priorityNum]]); // "HIGH"
console.log(Object.values(PRIORITIES).includes(priorityNum)); // false
console.log("HIGH" || false) // "HIGH" <- Expected output
// Based on the above code, the following code should output "HIGH" yet outputs 0, why does this happen?
console.log(PRIORITIES[NUM_TO_PRIORITY[priorityNum]] || Object.values(PRIORITIES).includes(priorityNum) ? priorityNum : PRIORITIES.low);
【问题讨论】:
-
请点击编辑,然后
[<>]sn-p编辑并发布minimal reproducible example -
感谢您的建议,添加了一个 sn-p 以防它帮助其他人:)
标签: javascript javascript-objects null-coalescing logical-or