天天看點

JavaScript優化

1、多個條件判斷

// Longhand

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

// logic

}

// Shorthand

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

2、為真...否則...

let test: boolean;

if (x > 100) {

test = true;

} else {

test = false;

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、為空檢查

if (test1 !== null || test1 !== undefined || test1 !== '') {

let test2 = test1;           

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'

繼續閱讀