gpt4 book ai didi

javascript - 当没有方法的返回值时,为什么 javaScript 的可选链接语法不适用于 Nullish Coalescing Operator?

转载 作者:行者123 更新时间:2023-12-05 00:36:25 25 4
gpt4 key购买 nike

我正在尝试新的 JavaScript 可选链接语法,它似乎与没有返回值的方法有问题。
例如:
我有一个带有 order 方法的餐厅对象:

const restaurant = {
order(i, k) {
console.log(`I was here with ${i} and ${k}`);
// does not return value
}
};
现在,如果我尝试检查以下餐厅对象中是否存在 order 方法,它会返回“undefiend”:
const orderCheck = restaurant.order?.(0, 1);
console.log(orderCheck ); // it returns undefined
现在的问题是,如果我将上述情况与 Nullish Coalescing Operator 一起使用,如下所示,它不起作用:
console.log(restaurant.order?.(0, 1) ?? 'Method does not exist');

Output:
I was here with 0 and 1
Method does not exist
问题:
现在上面语句中的问题是,可选链接语法甚至找到了排序方法并打印“我在这里有 0 和 1”,但仍然返回 'undefiend',这使得 Nullish Coalescing Operator 继续进行,甚至打印'方法不存在' 也作为默认值?
现在,如果我允许 order 方法返回一个值,那么它可以与 Nullish Coalescing Operator 一起正常工作并且它不会继续。
 const restaurant = {
order(i, k) {
console.log(`I was here with ${i} and ${k}`);
return '1';
}
};
如果再次检查:
console.log(restaurant.order?.(0, 1) ?? 'Method does not exist');

Output:
I was here with 0 and 1
可选链接语法是否有必要从方法中期望返回值而不是空值以检查其可用性?
在上述情况下,order 方法确实存在,那么如何防止 Nullish Coalescing Operator 不继续默认的“方法不存在”?
我正在使用现代浏览器(Chrome 和 firfox)对其进行测试,并且我还在 Chrome 中启用了 javaScript 实验性功能,但它仍然以上述方式工作。
有什么想法会有所帮助吗?谢谢

最佳答案

这与可选链接无关。

The Nullish Operator returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.


因此,可选链接已经在函数存在时工作,但它的返回值为 undefined ,因此运算符转到正确的部分。
笔记:
  • 函数内的日志显示为首先执行但没有返回任何值。
  • 如果函数不存在,在这种情况下它也将计算为 undefined由于 optional chaining 所以nullish operator的右边也会被采纳

  • let obj = {};
    console.log("function doesn't exist", obj?.foo?.(), obj?.foo?.() ?? 'right');

    obj = { foo: () => {} };
    console.log("function exists but doesn't return", obj?.foo?.(), obj?.foo?.() ?? 'right');

    obj = { foo: () => { return 'left'; } };
    console.log("function exists and returns", obj?.foo?.(), obj?.foo?.() ?? 'right');

    编辑:防止 Nullish Coalescing Operator 不继续默认的“方法不存在”即使方法存在

    obj = { foo: () => {} };
    console.log(obj?.foo && typeof obj.foo === 'function' ? obj.foo() : 'right');

    关于javascript - 当没有方法的返回值时,为什么 javaScript 的可选链接语法不适用于 Nullish Coalescing Operator?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69461922/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com