10個JS優(yōu)化小技巧

1. if多條件判斷

// 冗余
if (x === 'abc' || x === 'def' || x === 'ghi' || x ==='jkl') {}

// 簡潔
if (['abc', 'def', 'ghi', 'jkl'].includes(x)) {}

2. if...else...

// 冗余
let test: boolean;
if (x > 100) {
    test = true;
} else {
    test = false;
}

// 簡潔
let test = x > 10;

3. Null, Undefined, 空值檢查

// 冗余
if (first !== null || first !== undefined || first !== '') {
    let second = first;
}

// 簡潔
let second = first || '';

4. foreach循環(huán)

// 冗余
for (var i = 0; i < testData.length; i++)
    
// 簡潔
for (let i in testData)
// 或
for (let i of testData)

5. 函數(shù)條件調(diào)用

// 冗余
function test1() {
  console.log('test1');
};
function test2() {
  console.log('test2');
};
var test3 = 1;
if (test3 == 1) {
  test1();
} else {
  test2();
}

// 簡單
(test3 === 1? test1:test2)();

6. switch條件

// 冗余
switch (data) {
  case 1:
    test1();
  break;

  case 2:
    test2();
  break;

  case 3:
    test();
  break;
  // so on...
}

// 簡潔
var data = {
  1: test1,
  2: test2,
  3: test
};

data[anything] && data[anything]();

7. 多行字符串

// 冗余
const data = 'abc abc abc abc abc abc\n\t'
    + 'test test,test test test test\n\t'

// 簡潔
const data = `abc abc abc abc abc abc
         test test,test test test test`

8. 隱式返回

// 冗余
function getArea(diameter) {
  return Math.PI * diameter
}

// 簡潔
getArea = diameter => (
  Math.PI * diameter;
)

9. 重復(fù)字符串多次

// 冗余
let test = ''; 
for(let i = 0; i < 5; i ++) { 
  test += 'test '; 
} 

// 簡潔
'test '.repeat(5);

10. 冪乘

// 冗余
Math.pow(2,3);

// 簡潔而
2**3 // 8
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容