【问题标题】:How do you write this if/else statement for a boolean checker你如何为布尔检查器编写这个 if/else 语句
【发布时间】:2019-11-15 20:19:05
【问题描述】:

我有这些变量

    let isactive
    let istradeable = true
    let issellable = false
    let isrevocable
    let isburnable

我有一个 if/else,它主要查看这些变量并检查它们是否不为空,以及它是否未将其值分配给新变量。如果为 NULL,则将变量设置为 true

        if (isactive == null) {
        isactive = true
    } else {
        this.isactive = isactive
    }
    if (istradeable == null) {
        istradeable = true
    } else {
        this.istradeable = istradeable
    }
    if (issellable == null) {
        issellable = true
    } else {
        this.issellable = issellable
    }
    if (isrevocable == null) {
        isrevocable = true
    } else {
        this.isrevocable = isrevocable
    }
    if (isburnable == null) {
        isburnable = true
    } else {
        this.isburnable = isburnable
    }

这可行,但我正在寻找一个简单的函数,或者可能是一个更好的 if/else 语句来做同样的事情。谢谢大家!

【问题讨论】:

  • 由于您要更改变量本身的值,因此您必须编写的 if 语句数等于 {no of variables}。但是,如果您将变量分配给列表或对象,您可以编写一个 for 循环来为您工作。

标签: javascript if-statement


【解决方案1】:

我猜你在找

this.isactive = (isactive == null) ? true : isactive;
this.istradeable = (istradeable == null) ? true : istradeable;
this.issellable = (issellable == null) ? true : issellable;
this.isrevocable = (isrevocable == null) ? true : isrevocable;
this.isburnable = (isburnable == null) ? true : isburnable;

或更简单

this.isactive = isactive == null || isactive;
this.istradeable = istradeable == null || istradeable;
this.issellable = issellable == null || issellable;
this.isrevocable = isrevocable == null || isrevocable;
this.isburnable = isburnable == null || isburnable;

当然你也可以写一个函数:

function from(value) {
    if (value == null) return true;
    else return value;
}
this.isactive = from(isactive);
this.istradeable = from(istradeable);
this.issellable = from(issellable);
this.isrevocable = from(isrevocable);
this.isburnable = from(isburnable);

【讨论】:

    猜你喜欢
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-24
    • 1970-01-01
    • 1970-01-01
    • 2015-05-25
    相关资源
    最近更新 更多