天天看點

34個不可錯過的JavaScript代碼優化技巧

34個不可錯過的JavaScript代碼優化技巧

作者 | Jn_逆卷绫人

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

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

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

2、簡化 if true...else

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

// Longhand
let test: boolean;
if (x > 100) {
    test = true;
} else {
    test = false;
}
// Shorthand
let test = (x > 10) ? true : false;
//或者我們也可以直接用
let test = x > 10;
console.log(test);      

如果有嵌套的條件,可以這麼做。

let x = 300,
test2 = (x > 100) ? 'greater than 100' : (x < 50) ? 'less 50' : 'between 50 and 100';
console.log(test2); // "greater than 100"      

3、聲明變量

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

//Longhand 
let test1;
let test2 = 1;
//Shorthand 
let test1, test2 = 1;      

4、null、undefined 和空值檢查

當我們建立了新變量,有時候想要檢查引用的變量是不是為非 null 或 undefined。

JavaScript 确實有一個很好的快捷方式來實作這種檢查。

// Longhand
if (test1 !== null || test1 !== undefined || test1 !== '') {
    let test2 = test1;
}
// Shorthand
let test2 = test1 || '';      

5、 null 檢查和預設指派

let test1 = null,
    test2 = test1 || '';
console.log("null check", test2); // 輸出 ""      

6、 undefined 檢查和預設指派

let test1 = undefined,
    test2 = test1 || '';
console.log("undefined check", test2); // 輸出 ""      

一般值檢查

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

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

如果左邊值為 null 或 undefined,就傳回右邊的值。預設情況下,它将傳回左邊的值。

const test= null ?? 'default';
console.log(test);
// 輸出結果: "default"
const test1 = 0 ?? 2;
console.log(test1);
// 輸出結果: 0      

7、給多個變量指派

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

//Longhand 
let test1, test2, test3;
test1 = 1;
test2 = 2;
test3 = 3;
//Shorthand 
let [test1, test2, test3] = [1, 2, 3];      

8、簡便的指派操作符

在程式設計過程中,我們要處理大量的算術運算符。這是 JavaScript 變量指派操作符的有用技巧之一。

// Longhand
test1 = test1 + 1;
test2 = test2 - 1;
test3 = test3 * 20;
// Shorthand
test1++;
test2--;
test3 *= 20;      

9、 if 判斷值是否存在

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

// Longhand
if (test1 === true) or if (test1 !== "") or if (test1 !== null)
// Shorthand //檢查空字元串、null或者undefined
if (test1)      

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

10、 用于多個條件判斷的 && 操作符

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

//Longhand 
if (test1) {
 callMethod(); 
} 
//Shorthand 
test1 && callMethod();      

11、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      

12、比較後傳回

我們也可以在 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');
}      

13、 箭頭函數

//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);      

14、簡短的函數調用

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

// 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)();      

15、switch 簡化

我們可以将條件儲存在鍵值對象中,并根據條件來調用它們。

// Longhand
switch (data) {
  case 1:
    test1();
  break;
  case 2:
    test2();
  break;
  case 3:
    test();
  break;
  // ...
}
// Shorthand
var data = {
  1: test1,
  2: test2,
  3: test
};
data[something] && data[something]();      

16、隐式傳回

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

//longhand
function calculate(diameter) {
  return Math.PI * diameter
}
//shorthand
calculate = diameter => (
  Math.PI * diameter;
)      

17、 指數表示法

// Longhand
for (var i = 0; i < 10000; i++) { ... }
// Shorthand
for (var i = 0; i < 1e4; i++) {      

18、預設參數值

//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() //輸出結果: 3      

19、延展操作符簡化

//longhand
// 使用concat連接配接數組
const data = [1, 2, 3];
const test = [4 ,5 , 6].concat(data);
//shorthand
// 連接配接數組
const data = [1, 2, 3];
const test = [4 ,5 , 6, ...data];
console.log(test); // [ 4, 5, 6, 1, 2, 3]      

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

//longhand
// 克隆數組
const test1 = [1, 2, 3];
const test2 = test1.slice()
//shorthand
//克隆數組
const test1 = [1, 2, 3];
const test2 = [...test1];      

20、模闆字面量

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

//longhand
const welcome = 'Hi ' + test1 + ' ' + test2 + '.'
//shorthand
const welcome = `Hi ${test1} ${test2}`;      

21、跨行字元串

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

//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`      

22、對象屬性指派

let test1 = 'a'; 
let test2 = 'b';
//Longhand 
let obj = {test1: test1, test2: test2}; 
//Shorthand 
let obj = {test1, test2};      

23、将字元串轉成數字

//Longhand 
let test1 = parseInt('123'); 
let test2 = parseFloat('12.3'); 
//Shorthand 
let test1 = +'123'; 
let test2 = +'12.3';      

24、解構指派

//longhand
const test1 = this.data.test1;
const test2 = this.data.test2;
const test2 = this.data.test3;
//shorthand
const { test1, test2, test3 } = this.data;      

25、數組 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' }      

26、條件查找簡化

如果我們要基于不同的類型調用不同的方法,可以使用多個 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();      

27、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
}      

28、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' ]
]
**/      

29、Object.values()

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

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

30、雙重按位操作

// Longhand
Math.floor(1.9) === 1 // true
// Shorthand
~~1.9 === 1 // true      

31、重複字元串多次

為了重複操作相同的字元,我們可以使用 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);      

32、查找數組的最大值和最小值

const arr = [1, 2, 3]; 
Math.max(…arr); // 3
Math.min(…arr); // 1      

33、擷取字元串的字元

let str = 'abc';
//Longhand 
str.charAt(2); // c
//Shorthand 
str[2]; // c      

34、 指數幂簡化

//longhand
Math.pow(2,3); // 8
//shorthand
2**3 // 8      

本文完~

學習更多技能

請點選下方公衆号