在javascript中简化if .. else

时间:2012-06-08 10:30:58

标签: javascript

我的思绪是空白的,我想不出解决方案......

我有以下代码:

if (onlySelected === true) {
    if (r.selected == true) {
        result.push(pushValue);
    }
}
else {
    result.push(pushValue);
}

如何将此代码简化为:

if (condition) { result.push(pushValue) } 

5 个答案:

答案 0 :(得分:8)

试试这个:

if (!onlySelected || r.selected){
    result.push(pushValue);
}

或者如果你绝对需要类型相等而不仅仅是真实性:

if (onlySelected !== true || r.selected){
    result.push(pushValue);
}

答案 1 :(得分:0)

if(onlySelected === false || r.selected == true) {
    result.push(pushValue);
}

答案 2 :(得分:0)

(!onlySelected || r.selected) && result.push(pushValue);

答案 3 :(得分:0)

if( (onlySelected === true && r.selected === true) || 1) {
    result.push(value)
}

答案 4 :(得分:0)

我认为这样可行:

if(!onlySelected || (onlySelected && r.selected))
    result.push(pushValue);