Shorthand if/else statement Javascript

前端 未结 7 1424
难免孤独
难免孤独 2020-12-07 16:57

I\'m wondering if there\'s a shorter way to write this:

var x = 1;
if(y != undefined) x = y;

I initially tried x = y || 1, but

7条回答
  •  时光取名叫无心
    2020-12-07 17:04

    Another way to write it shortly

    bePlanVar = !!((bePlanVar == false));
    
    // is equivalent to
    
    bePlanVar = (bePlanVar == false) ? true : false;
    
    // and 
    
    if (bePlanVar == false) {
        bePlanVar = true;
    } else {
        bePlanVar = false;
    }
    

提交回复
热议问题