JS:简化运算

三元运算

1
2
3
4
5
6
7
8
let type;
if(type === 'a') {
type = 'typeA';
} else if (type === 'b') {
type = 'typeB'
}
// 简化
let type = type === 'a' ? 'typeA' : 'typeB'

四元运算

1
2
3
4
5
6
7
8
9
10
let type;
if(type === 'a') {
type = 'typeA';
} else if (type === 'b') {
type = 'typeB'
} else if (type === 'c') {
type = 'typeC'
}
// 简化
let type = type === 'a' ? 'typeA' : (type === 'b' ? 'typeB' : 'typeC')
-------------本文结束 感谢您的阅读-------------