1

OR通过ing 一个字符串(通过PRIORITIES[NUM_TO_PRIORITY[priorityNum]]where priorityNumis 输入)和一个字符串(通过 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);

4

2 回答 2

3

正如另一个答案中提到的,这是由于运算符优先级。

valOne || valTwo ? priorityNum : PRIORITIES.low;

是相同的:

(valOne || valTwo) ? priorityNum : PRIORITIES.low;

但你想要:

valOne || (valTwo ? priorityNum : PRIORITIES.low);

由于大多数没有记住 20 多个运算符的优先级,因此可以通过使用更多括号(如上所示)或更多变量来避免这些错误:

const PRIORITIES = {
    high: 'HIGH',
    low: 'LOW',
};
const NUM_TO_PRIORITY = {
    0: 'high',
    1: 'low',
};
const priorityNum = 0;

const priority = PRIORITIES[NUM_TO_PRIORITY[priorityNum]]
const otherVal = Object.values(PRIORITIES).includes(priorityNum) ? priorityNum : PRIORITIES.low

priority || otherVal; // "HIGH"
于 2020-04-14T16:57:25.630 回答
2

||高于operator precedence?因此您的代码被评估为

(PRIORITIES[NUM_TO_PRIORITY[priorityNum]] || Object.values(PRIORITIES).includes(priorityNum))  ? priorityNum : PRIORITIES.low

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
// "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);

于 2020-04-14T16:55:17.767 回答