OR
通过ing 一个字符串(通过PRIORITIES[NUM_TO_PRIORITY[priorityNum]]
where priorityNum
is 输入)和一个字符串(通过 conditional )进行空值合并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);