【问题标题】:Messing with ternary operator与三元运算符混淆
【发布时间】:2020-10-25 05:26:15
【问题描述】:

我想将函数中的 if 语句转换为三元运算符。这个功能是选择任意元素。

function s(el, index, all){
    if(el !== undefined && index === undefined)
        return document.querySelector(el);
    else if(el !== undefined && index !== undefined && all === true)
        return document.querySelectorAll(el);
    else
        return document.querySelectorAll(el)[index];
}

【问题讨论】:

标签: conditional-operator


【解决方案1】:

你可以像这样干净利落地做到这一点

function s(el, index, all){
    let firstCondition = el !== undefined && index === undefined;
    let secondCondition = el !== undefined && index !== undefined && all === true;
    return firstCondition ? document.querySelector(el) : secondCondition ? document.querySelectorAll(el) : document.querySelectorAll(el)[index];
}

【讨论】:

    【解决方案2】:
    return (el !== undefined && index === undefined)?document.querySelector(el):(el !== undefined && index !== undefined && all === true)?document.querySelectorAll(el):document.querySelectorAll(el)[index];
    

    【讨论】:

    • 条件 A ?值A:条件B?值 B:条件 C?值 C :.... 如果条件 A 为真,则选择值 A,否则检查条件 B。如果条件 B 为真,则选择 B,否则检查条件 C,依此类推。
    猜你喜欢
    • 2014-02-08
    • 2012-02-13
    • 2012-03-09
    • 2021-12-30
    • 1970-01-01
    • 2018-04-01
    • 1970-01-01
    • 2012-12-15
    • 1970-01-01
    相关资源
    最近更新 更多