作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试新的 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
问题:
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
可选链接语法是否有必要从方法中期望返回值而不是空值以检查其可用性?
最佳答案
这与可选链接无关。
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');
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/
我正在尝试用 Swift 编写这段 JavaScript 代码:k_combinations 到目前为止,我在 Swift 中有这个: import Foundation import Cocoa e
我是一名优秀的程序员,十分优秀!