1
if(bool){
a =1;
}else{
a=2
}
// 简写
a= bool ? 1 : 2
2
if(bool){
a=fn()
}
//简写
bool && (a=fn())
if(!bool) {
a=fn()
}
//简写
bool || (a=fn())
3
if(b===1){
a='one'
} else if (b===2) {
a='two'
} else {
return ''
}
//简写
let res ={1:'one',2:'two'}
a= res[key] ? res[key] : '';
4
function fn(a){
if(a==='x'){
doX();
}else if(a==='y'){
doY();
}else{
doZ();
}
}
//简写
function fn(a){
let lookup={x:doX:y:doY},def=doZ;
lookup[a] ? lookup[a]() : def();
}
5.if多条件
if (x === 'abc' || x === 'def' || x === 'ghi' || x ==='jkl') {}
// 简写
if (['abc', 'def', 'ghi', 'jkl'].includes(x)) {}
6.forEach循环
for (var i = 0; i < testData.length; i++)
// 简写
for (let i in testData)
// 或
for (let i of testData)
7.隐式返回
function getArea(diameter) {
return Math.PI * diameter
}
// 简洁
getArea = diameter => (
Math.PI * diameter;
)
评论区