【问题标题】:Javascript: Initialize a variable by condition [duplicate]Javascript:按条件初始化变量[重复]
【发布时间】:2021-08-19 12:28:15
【问题描述】:

我想用某个字段的值来初始化一个变量类型:

function checkAfterPrereqChange(blfType, blfId){
    const type = $("#fieldTypeInput"+blfId).val();
}

问题是这个字段只有在 blfType 是 'field' 时才存在,如果不是 type 应该是 blfType 的值,像这样:

function checkAfterPrereqChange(blfType, blfId){
    let type = blfType;
    if (blfType == "field"){
        let type = $("#fieldTypeInput"+blfId).val();
    }
}

我仍然可以仅在一行中使用 const 变量来执行此操作吗? 在 Python 中,我会这样做:

type = $("#fieldTypeInput"+blfId).val() if blfType == "field" else blfType

有没有办法在 Javascript 中也能做到这一点?

【问题讨论】:

    标签: javascript jquery one-liner


    【解决方案1】:

    const type = blfType === "field" ? $("#fieldTypeInput"+blfId).val() : blfType

    【讨论】:

      【解决方案2】:

      使用conditional operator:

      const type = blfType === "field" ? $("#fieldTypeInput"+blfId).val() : blfType
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-07-26
        • 2017-09-21
        • 1970-01-01
        • 2015-12-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多