2021 年不可錯過的 34 種 JS 優化技巧

作者丨 Atit

譯者丨王者

轉載丨前端之巔

開發者總是在學習新東西,而跟上這些技術的變化不應該比之前更難。我寫這篇文章的目的是介紹 JavaScript 的一些最佳實踐,作爲前端開發人員,掌握了這些最佳實踐會讓我們在 2021 年的工作變得更輕鬆。

你可能做了很長時間的 JavaScript 開發,但有時候你可能沒有使用最新的 JavaScript 特性或技巧,這些特性和技巧可以在不需要編寫額外代碼的情況下解決你的問題。它們可以幫助你寫出乾淨且優化的 JavaScript 代碼。此外,如果你在 2021 年準備去參加面試,可以參考本文的內容。

  1. 帶有多個條件的 if 語句

把多個值放在一個數組中,然後調用數組的 includes 方法。

//longhand
if (x === 'abc' || x === 'def' || x === 'ghi' || x ==='jkl') {
    //logic
}
//shorthand
if (['abc', 'def', 'ghi', 'jkl'].includes(x)) {
   //logic
}
  1. 簡化 if true...else

對於不包含大邏輯的 if-else 條件,可以使用下面的快捷寫法。我們可以簡單地使用三元運算符來實現這種簡化。

// 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"
  1. 聲明變量

當我們想要聲明兩個具有相同的值或相同類型的變量時,可以使用這種簡寫。

//Longhand 
let test1;
let test2 = 1;
//Shorthand 
let test1, test2 = 1;
  1. null、undefined 和空值檢查

當我們創建了新變量,有時候想要檢查引用的變量是不是爲非 null 或 undefined。JavaScript 確實有一個很好的快捷方式來實現這種檢查。

// Longhand
if (test1 !== null || test1 !== undefined || test1 !== '') {
    let test2 = test1;
}
// Shorthand
let test2 = test1 || '';
  1. null 檢查和默認賦值
let test1 = null,
    test2 = test1 || '';
console.log("null check", test2); // output will be ""
  1. undefined 檢查和默認賦值
let test1 = undefined,
    test2 = test1 || '';
console.log("undefined check", test2); // output will be ""

一般值檢查

let test1 = 'test',
    test2 = test1 || '';
console.log(test2); // output: 'test'

另外,對於上述的 4、5、6 點,都可以使用?? 操作符。

如果左邊值爲 null 或 undefined,就返回右邊的值。默認情況下,它將返回左邊的值。

const test= null ?? 'default';
console.log(test);
// expected output: "default"
const test1 = 0 ?? 2;
console.log(test1);
// expected output: 0
  1. 給多個變量賦值

當我們想給多個不同的變量賦值時,這種技巧非常有用。

//Longhand 
let test1, test2, test3;
test1 = 1;
test2 = 2;
test3 = 3;
//Shorthand 
let [test1, test2, test3] = [1, 2, 3];
  1. 簡便的賦值操作符

在編程過程中,我們要處理大量的算術運算符。這是 JavaScript 變量賦值操作符的有用技巧之一。

// Longhand
test1 = test1 + 1;
test2 = test2 - 1;
test3 = test3 * 20;
// Shorthand
test1++;
test2--;
test3 *= 20;
  1. if 判斷值是否存在

這是我們都在使用的一種常用的簡便技巧,在這裏仍然值得再提一下。

// Longhand
if (test1 === true) or if (test1 !== "") or if (test1 !== null)
// Shorthand //it will check empty string,null and undefined too
if (test1)

注意:如果 test1 有值,將執行 if 之後的邏輯,這個操作符主要用於 null 或 undefinded 檢查。

  1. 用於多個條件判斷的 && 操作符

如果只在變量爲 true 時才調用函數,可以使用 && 操作符。

//Longhand 
if (test1) {
 callMethod(); 
} 
//Shorthand 
test1 && callMethod();
  1. for each 循環

這是一種常見的循環簡化技巧。

// Longhand
for (var i = 0; i < testData.length; i++)
// Shorthand
for (let i in testData) or  for (let i of testData)

遍歷數組的每一個變量。

function testData(element, index, array) {
  console.log('test[' + index + '] = ' + element);
}
[11, 24, 32].forEach(testData);
// logs: test[0] = 11, test[1] = 24, test[2] = 32
  1. 比較後返回

我們也可以在 return 語句中使用比較,它可以將 5 行代碼減少到 1 行。

// Longhand
let test;
function checkReturn() {
    if (!(test === undefined)) {
        return test;
    } else {
        return callMe('test');
    }
}
var data = checkReturn();
console.log(data); //output test
function callMe(val) {
    console.log(val);
}
// Shorthand
function checkReturn() {
    return test || callMe('test');
}
  1. 箭頭函數
//Longhand 
function add(a, b) { 
   return a + b; 
} 
//Shorthand 
const add = (a, b) => a + b;

更多例子:

function callMe(name) {
  console.log('Hello', name);
}
callMe = name => console.log('Hello', name);
  1. 簡短的函數調用

我們可以使用三元操作符來實現多個函數調用。

// Longhand
function test1() {
  console.log('test1');
};
function test2() {
  console.log('test2');
};
var test3 = 1;
if (test3 == 1) {
  test1();
} else {
  test2();
}
// Shorthand
(test3 === 1? test1:test2)();
  1. switch 簡化

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

// Longhand
switch (data) {
  case 1:
    test1();
  break;
  case 2:
    test2();
  break;
  case 3:
    test();
  break;
  // And so on...
}
// Shorthand
var data = {
  1: test1,
  2: test2,
  3: test
};
data[something] && data[something]();
  1. 隱式返回

通過使用箭頭函數,我們可以直接返回值,不需要 return 語句。

//longhand
function calculate(diameter) {
  return Math.PI * diameter
}
//shorthand
calculate = diameter => (
  Math.PI * diameter;
)
  1. 指數表示法
// Longhand
for (var i = 0; i < 10000; i++) { ... }
// Shorthand
for (var i = 0; i < 1e4; i++) {
  1. 默認參數值
//Longhand
function add(test1, test2) {
  if (test1 === undefined)
    test1 = 1;
  if (test2 === undefined)
    test2 = 2;
  return test1 + test2;
}
//shorthand
add = (test1 = 1, test2 = 2) => (test1 + test2);
add() //output: 3
  1. 延展操作符簡化
//longhand
// joining arrays using concat
const data = [1, 2, 3];
const test = [4 ,5 , 6].concat(data);
//shorthand
// joining arrays
const data = [1, 2, 3];
const test = [4 ,5 , 6, ...data];
console.log(test); // [ 4, 5, 6, 1, 2, 3]

我們也可以使用延展操作符進行克隆。

//longhand
// cloning arrays
const test1 = [1, 2, 3];
const test2 = test1.slice()
//shorthand
// cloning arrays
const test1 = [1, 2, 3];
const test2 = [...test1];
  1. 模板字面量

如果你厭倦了使用 + 將多個變量連接成一個字符串,那麼這個簡化技巧將讓你不再頭痛。

//longhand
const welcome = 'Hi ' + test1 + ' ' + test2 + '.'
//shorthand
const welcome = `Hi ${test1} ${test2}`;
  1. 跨行字符串

當我們在代碼中處理跨行字符串時,可以這樣做。

//longhand
const data = 'abc abc abc abc abc abc\n\t'
    + 'test test,test test test test\n\t'
//shorthand
const data = `abc abc abc abc abc abc
         test test,test test test test`
  1. 對象屬性賦值
let test1 = 'a'; 
let test2 = 'b';
//Longhand 
let obj = {test1: test1, test2: test2}; 
//Shorthand 
let obj = {test1, test2};
  1. 將字符串轉成數字
//Longhand 
let test1 = parseInt('123'); 
let test2 = parseFloat('12.3'); 
//Shorthand 
let test1 = +'123'; 
let test2 = +'12.3';
  1. 解構賦值
//longhand
const test1 = this.data.test1;
const test2 = this.data.test2;
const test2 = this.data.test3;
//shorthand
const { test1, test2, test3 } = this.data;
  1. 數組 find 簡化

當我們有一個對象數組,並想根據對象屬性找到特定對象,find 方法會非常有用。

const data = [{
        type: 'test1',
        name: 'abc'
    },
    {
        type: 'test2',
        name: 'cde'
    },
    {
        type: 'test1',
        name: 'fgh'
    },
]
function findtest1(name) {
    for (let i = 0; i < data.length; ++i) {
        if (data[i].type === 'test1' && data[i].name === name) {
            return data[i];
        }
    }
}
//Shorthand
filteredData = data.find(data => data.type === 'test1' && data.name === 'fgh');
console.log(filteredData); // { type: 'test1', name: 'fgh' }
  1. 條件查找簡化

如果我們要基於不同的類型調用不同的方法,可以使用多個 else if 語句或 switch,但有沒有比這更好的簡化技巧呢?

// Longhand
if (type === 'test1') {
  test1();
}
else if (type === 'test2') {
  test2();
}
else if (type === 'test3') {
  test3();
}
else if (type === 'test4') {
  test4();
} else {
  throw new Error('Invalid value ' + type);
}
// Shorthand
var types = {
  test1: test1,
  test2: test2,
  test3: test3,
  test4: test4
};
var func = types[type];
(!func) && throw new Error('Invalid value ' + type); func();
  1. indexOf 的按位操作簡化

在查找數組的某個值時,我們可以使用 indexOf() 方法。但有一種更好的方法,讓我們來看一下這個例子。

//longhand
if(arr.indexOf(item) > -1) { // item found 
}
if(arr.indexOf(item) === -1) { // item not found
}
//shorthand
if(~arr.indexOf(item)) { // item found
}
if(!~arr.indexOf(item)) { // item not found
}

按位 (~) 運算符將返回 true(-1 除外),反向操作只需要!~。另外,也可以使用 include() 函數。

if (arr.includes(item)) { 
// true if the item found
}
  1. Object.entries()

這個方法可以將對象轉換爲對象數組。

const data = { test1: 'abc', test2: 'cde', test3: 'efg' };
const arr = Object.entries(data);
console.log(arr);
/** Output:
[ [ 'test1', 'abc' ],
  [ 'test2', 'cde' ],
  [ 'test3', 'efg' ]
]
**/
  1. Object.values()

這也是 ES8 中引入的一個新特性,它的功能類似於 Object.entries(),只是沒有鍵。

const data = { test1: 'abc', test2: 'cde' };
const arr = Object.values(data);
console.log(arr);
/** Output:
[ 'abc', 'cde']
**/
  1. 雙重按位操作
// Longhand
Math.floor(1.9) === 1 // true
// Shorthand
~~1.9 === 1 // true
  1. 重複字符串多次

爲了重複操作相同的字符,我們可以使用 for 循環,但其實還有一種簡便的方法。

//longhand 
let test = ''; 
for(let i = 0; i < 5; i ++) { 
  test += 'test '; 
} 
console.log(str); // test test test test test 
//shorthand 
'test '.repeat(5);
  1. 查找數組的最大值和最小值
const arr = [1, 2, 3]; 
Math.max(…arr); // 3
Math.min(…arr); // 1
  1. 獲取字符串的字符
let str = 'abc';
//Longhand 
str.charAt(2); // c
//Shorthand 
str[2]; // c
  1. 指數冪簡化
//longhand
Math.pow(2,3); // 8
//shorthand
2**3 // 8

原文鏈接:

https://javascript.plainenglish.io/34-javascript-optimization-techniques-to-know-in-2021-d561afdf73c3

推薦閱讀:

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/pVXSknPNX0VT_2JnxSOSHw