JS——if else的简洁写法


第一种省略括号

/*
* * js 判断的几种写法 */ var a = 10,b = 20; console.log(a); console.log(b); /*最直接*/ if(a > b){ console.log('a大'); }else{ console.log('b大'); }; /*改变1*/ if(a > b) console.log('a大'); if(a < b) console.log('b大'); /*改变2*/ if(a > b) console.log('a大'); else console.log('b大'); /*最简单*/
或者使用常见的三元操作符 
console.log(a>b ? 'a大' : 'b大');

第二种使用对象形式

假如我们有这样一段逻辑:

let orderStatus = ''
 
if (res.data.status == '1') {
    orderStatus = '待付款'
} else if (res.data.status == '2') {
    orderStatus == '待发货'
} else if (res.data.status == '3') {
    orderStatus == '已发货'
} else if (res.data.status == '4') {
    orderStatus == '待收货'
} else if (res.data.status == '5'){
    orderStatus == '已完成'
}

可以简写为:

let orderStatus
let map = { '1': '待付款', '2': '待发货', '3': '已发货', '4': '待收货','5':'已完成'}
orderStatus = map[res.data.status]

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM