2 回答

TA貢獻1817條經驗 獲得超14個贊
這是一個優先級問題。您的代碼被評估為:
if (data?.["myKeys"]?.indexOf("index1") ?? (-1 === -1)) {
// ????????????????????????????????????????^?????????^
console.log("Why is it true");
}
但你的意圖是:
if ((data?.["myKeys"]?.indexOf("index1") ?? -1) === -1) {
// ?^?????????????????????????????????????????^
console.log("Why is it true");
}
奇怪的是,我沒有看到提案中討論的優先級,盡管它在規范草案中如喬納斯提到的那樣被提及,并且它確實出現在問題中。
如您所見,這與 的優先級一致||,這是它的非常非常近的親戚:
const a = 2;
const b = -1;
console.log(`${a} || $ === $: ${a || b === b}`);
console.log(`(${a} || $) === $: ${(a || b) === b}`);
console.log(`${a} || ($ === $): ${a || (b === b)}`);
根據草案規范,??優先級低于||(大概只是更低)。(為避免混淆,也不允許在&&or||表達式中。)
添加回答
舉報