【问题标题】:Return shorthand if assignment is false in JavaScript?如果 JavaScript 中的赋值为假,则返回简写?
【发布时间】:2020-12-19 11:20:18
【问题描述】:

在 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...

这有可能的简写吗?

【问题讨论】:

  • 如果返回void 0,为什么要return?我会颠倒逻辑:if (A) { // things... }。否则返回是隐含的。
  • 您不能在操作数中包含语句,这就是第二个示例不起作用的原因。找速记有什么意义?不要最小化您的开发代码,在创建生产代码时,一个缩小器会为您完成。
  • if后面有代码吗?
  • 可以使用单行if。在您的第二个示例中,而不是 !A || return; 使用 if (!A) return;
  • @briosheje 这是因为这些是检查,代码中有多个检查,它会返回。通过在开头添加条件并在任何失败时返回,代码更清晰。

标签: javascript return coalesce shorthand


【解决方案1】:

不幸的是,没有这样的速记。 return 是一个语句,而不是一个表达式,并且有条件地评估语句的唯一方法是 if。运算符(AND、OR、三元等)可以帮助您评估表达式,但不能帮助您评估语句

【讨论】:

    【解决方案2】:

    取决于实际代码

    • 如果它只是返回或应该返回一个值
    • 关于多少个地方
    • 之前的代码是什么(例如要进一步使用的变量)
    • 后面是什么代码
    • 等。等等……

    可以使用以下方法。

    return !A || theRestOfTheCodePutIntoAnotherFunction();而不是if (!A) return;或(不工作)!A || return;

    “原始”代码示例:

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

    【讨论】:

      猜你喜欢
      • 2016-12-21
      • 2019-09-29
      • 2021-10-15
      • 1970-01-01
      • 1970-01-01
      • 2018-07-29
      • 1970-01-01
      • 2017-04-01
      • 2016-05-03
      相关资源
      最近更新 更多