问题描述
在JavaScript函数中,如果给定值为null,我想返回。
这可行:
const A = this.B;
if (!A) {
return;
}
// More code...
我想知道是否有一种更简单的形式来做到这一点:
这些无效:
const A = this.B || return;
// More code...
const A = this.B;
!A || return;
// More code...
这可能有一个简写吗?
解决方法
不幸的是,没有这样的简写。 return
是语句,而不是表达式,并且有条件地评估语句的唯一方法是if
。运算符(AND,OR,三元等)可以帮助您评估表达式,但不能评估语句
取决于实际代码:
- 如果它只是返回或应该返回一个值
- 在几个地方
- 之前的代码是什么(例如要进一步使用的变量)
- 后面的代码是什么
- 等等等...
可以使用以下方法。
您if (!A) return;
代替!A || return;
或(不起作用)return !A || theRestOfTheCodePutIntoAnotherFunction();
“原始”代码示例:
class Test {
constructor(b) {
this.b = b
}
test() {
const a = this.b
if (!a) {
return
}
console.log("TEST")
}
}
console.log("test 0")
new Test(0).test()
console.log("test 1")
new Test(1).test()
和修改版本
class Test {
constructor(b) {
this.b = b
}
test() {
const a = this.b
return !a || this.test2()
}
test2() {
console.log("TEST")
}
}
console.log("test 0")
new Test(0).test()
console.log("test 1")
new Test(1).test()