2023 年你需要了解的 JavaScript 代碼技巧

分享一些我常用的代碼優化技巧,希望對你有幫助。

1. 多表達式多 if 判斷

我們可以在數組中存儲多個值,並且可以使用數組 include 方法。

// 長
if (x === 'abc' || x === 'def' || x === 'ghi' || x ==='jkl') {
  //logic
}
// 短
if (['abc', 'def', 'ghi', 'jkl'].includes(x)) {
  //logic
}

2. 簡寫 if else

如果 if-else 的邏輯比較簡單,可以使用下面這種方式鏡像簡寫,當然也可以使用三元運算符來實現。

// 長
let test: boolean;
if (x > 100) {
  test = true;
} else {
  test = false;
}
// 短
let test = (x > 10) ? true : false;
// 也可以直接這樣
let test = x > 10;

3. 合併變量聲明

當我們聲明多個同類型的變量時,可以像下面這樣簡寫。

// 長 
let test1;
let test2 = 1;
// 短 
let test1, test2 = 1;

4. 合併變量賦值

當我們處理多個變量並將不同的值分配給不同的變量時,這種方式非常有用。

// 長 
let test1, test2, test3;
test1 = 1;
test2 = 2;
test3 = 3;
// 短 
let [test1, test2, test3] = [1, 2, 3];

5. && 運算符

如果僅在變量值爲 true 的情況下才調用函數,則可以使用 && 運算符。

// 長 
if (test1) {
 callMethod(); 
} 
// 短 
test1 && callMethod();

6. 箭頭函數

// 長  
function add(a, b) { 
   return a + b; 
} 
// 短 
const add = (a, b) => a + b;

7. 短函數調用

可以使用三元運算符來實現這些功能。

const fun1 = () => console.log('fun1');
const fun2 = () => console.log('fun2');
// 長
let test = 1;
if (test == 1) {
  fun1();
} else{
  fun2();
}
// 短
(test === 1? fun1:fun2)();

8. Switch 簡記法

我們可以將條件保存在鍵值對象中,並可以根據條件使用。

// 長
switch (data) {
  case 1:
    test1();
  break;
  case 2:
    test2();
  break;
  case 3:
    test();
  break;
  // And so on...
}
// 短
const data = {
  1: test1,
  2: test2,
  3: test
};
data[something] && data[something]();

9. 默認參數值

// 長
function add(test1, test2) {
  if (test1 === undefined)
    test1 = 1;
  if (test2 === undefined)
    test2 = 2;
  return test1 + test2;
}
// 短
const add = (test1 = 1, test2 = 2) => (test1 + test2);

10. 擴展運算符

// 長-合併數組
const data = [1, 2, 3];
const test = [4 ,5 , 6].concat(data);
// 短-合併數組
const data = [1, 2, 3];
const test = [4 ,5 , 6, ...data];
// 長-拷貝數組
const test1 = [1, 2, 3];
const test2 = test1.slice()
// 短-拷貝數組
const test1 = [1, 2, 3];
const test2 = [...test1];

11. 模版字符串

// 長
const welcome = 'Hi ' + test1 + ' ' + test2 + '.'
// 短
const welcome = `Hi ${test1} ${test2}`;

12. 簡寫對象

let test1 = 'a'; 
let test2 = 'b';
// 長 
let obj = {test1: test1, test2: test2}; 
// 短 
let obj = {test1, test2};

13. 在數組中查找最大值和最小值

const arr = [1, 2, 3]; 
Math.max(arr); // 3
Math.min(arr); // 1
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/WYazZhFFPdqKcmCuc7ittA