1、多个条件判断
// Longhand
if (x === 'abc' || x === 'def' || x === 'ghi' || x ==='jkl') {
// logic
}
// Shorthand
if (['abc', 'def', 'ghi', 'jkl'].includes(x)) {
// logic
}
2、为真...否则...
// Longhand
let test: boolean;
if (x > 100) {
test = true;
} else {
test = false;
}
// Shorthand
let test = (x > 10) ? true : false;
//or we can use directly
let test = x > 10;
console.log(test);
或者
let x = 300,
test2 = (x > 100) ? 'greater 100' : (x < 50) ? 'less 50' : 'between 50 and 100';
console.log(test2); // "greater than 100"
3、为null、为undefined、为空检查
// Longhand
if (test1 !== null || test1 !== undefined || test1 !== '') {
let test2 = test1;
}
// Shorthand
let test2 = test1 || '';
4、null值检查和分配默认值
let test1 = null,
test2 = test1 || '';
console.log("null check", test2); // output will be ""
5、undefined值检查和分配默认值
let test1 = undefined,
test2 = test1 || '';
console.log("undefined check", test2); // output will be ""
6、正常值检查
let test1 = 'test',
test2 = test1 || '';
console.log(test2); // output: 'test'
// Longhand
if (x === 'abc' || x === 'def' || x === 'ghi' || x ==='jkl') {
// logic
}
// Shorthand
if (['abc', 'def', 'ghi', 'jkl'].includes(x)) {
// logic
}