简体   繁体   English

如果 JavaScript 中的赋值为 false,则返回简写?

[英]Return shorthand if assignment is false in JavaScript?

In a JavaScript function I would like to return if a given value is null.在 JavaScript 函数中,如果给定值为 null,我想返回。

While this works:虽然这有效:

const A = this.B;

if (!A) {
   return;
}

// More code...

I would like to know if there's a simpler form to do this:我想知道是否有更简单的形式来做到这一点:

These don't work:这些不起作用:

const A = this.B || return;

// More code...
const A = this.B;
                                                                                   
!A || return;

// More code...

Is there a possible shorthand for this?这有可能的简写吗?

Unfortunately there is no such shorthand.不幸的是,没有这样的速记。 return is a statement, not an expression, and the only way to evaluate statements conditionally is if . return是一个语句,而不是一个表达式,并且有条件地评估语句的唯一方法是if Operators (AND, OR, ternary and so on) can help you evaluate expressions, but not statements运算符(AND、OR、三元等)可以帮助您评估表达式,但不能帮助您评估语句

Depending on actual code :取决于实际代码

  • if it just returns or should return a value如果它只是返回或应该返回一个值
  • on how many places在多少个地方
  • what code is before (eg variables to be used further)之前是什么代码(例如要进一步使用的变量)
  • what code is after什么代码之后
  • etc. etc...等等等等...

the following approach can be used.可以使用以下方法。

Instead of if (!A) return;而不是if (!A) return; or (not working) !A || return;或(不工作) !A || return; !A || return; , you return !A || theRestOfTheCodePutIntoAnotherFunction(); , 你return !A || theRestOfTheCodePutIntoAnotherFunction(); return !A || theRestOfTheCodePutIntoAnotherFunction();

An example of "original" code: “原始”代码示例:

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()

and modified version和修改版本

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM