if简洁干净

if判断不等于(多个)的情况:|| ' '

<script type="text/javascript">
    const test1 = 'wowowowowo'
    if (test1 !==null | test1 !==undefined | test1 !== '') {
        var test2 = test1
    }
    //直接js这样就可以了
    let test3 = test1 || ''
    console.log(test2)//wowowowowo
    console.log(test3)//wowowowowo
</script>

if判断之后赋值的情况:三元替换

<script type="text/javascript">
    let x = 1
    if (x > 10) {
        test = true;
    } else {
        test = false;
    }
    let test = (x > 10) ? true : false;
    console.log(test) //大于10返回true,不是false
</script>

if判断等于(多个)的情况:includes

if (x === 'abc' || x === 'def' || x === 'ghi' || x ==='jkl') {
    //logic
}

if (['abc', 'def', 'ghi', 'jkl'].includes(x)) {
   //logic
}

&&简化if

<script type="text/javascript">
    
    let test = 11
    
    if(test>10){
        console.log(10)//10
    }
    
    test > 10 && console.log(10)//10 test大于10会执行&&右边的方法
</script>

操作符

test1 = test1 + 1;
test2 = test2 - 1;
test3 = test3 * 20;
test1++;
test2--;
test3 *= 20

 

posted @ 2021-04-23 17:32  青眼魔术  阅读(72)  评论(0编辑  收藏  举报