javascript - 简写:如果不是 false 则分配 javascript
问题描述
看看我所做的事情的速记是否普遍存在。
我通常编写/使用函数,如果不能做他们能够做的事情,它们将返回 false,但如果可以,则返回一个对象。我也可能通常想检查是否成功。
例如。
function someFunc() {
// assume a is some object containing objects with or without key b
// edit: and that a[b] is not going to *want* to be false
function getAB(a, b) {
if(a[b]) return a[b];
return false;
}
let ab = getAB(a, b);
if(!ab) return false;
}
我只是想知道是否有某种速记。例如,在幻想世界中,
//...
let ab = getAB(a, b) || return false
//...
解决方案
您可以使用 or 运算符,例如:
return a[b] || false
您的完整示例代码可以写成:
function someFunc() {
// assume a is some object containing objects with or without key b
function getAB(a, b) {
return a[b] || false
}
return getAB(a, b); // getAB already returns the value, no need to check again.
}
推荐阅读
- qt - 如何取消选择 QTabBar 中的所有选项卡?
- flutter - 如何使工具提示形状使用路径?
- java - 多模块项目中的 Gradle 构建错误:java.lang.NoClassDefFoundError: at groovyjarjarasm.asm.signature.SignatureReader.parseType
- python - 如何使用两个日期之间的特定差异从表中选择行?
- google-analytics-4 - 跟踪 Google Analytics Cookie 接受拒绝按钮点击
- python-3.x - 抓取 cdkeys[dot]com
- angular - Angular 材质媒体时间轴组件
- javascript - 错误报告:当 LineSeries 包含相同的数字时,ScrollStrategies 不起作用
- validation - 如何使用 assertJ 测试 ContraintViolationException?
- angular-material - 在特定要求下如何隐藏属性?