首頁  >  文章  >  web前端  >  18個你需要知道的JavaScript優化技巧

18個你需要知道的JavaScript優化技巧

WBOY
WBOY轉載
2021-12-14 18:49:361628瀏覽

這篇文章我們一起來看一下JavaScript的18個優化技巧,適合所有正在使用JavaScript 程式設計的開發人員閱讀,本文的目的在於幫助大家更加熟練的運用JavaScript 語言來進行開發工作,希望對大家有幫助。

18個你需要知道的JavaScript優化技巧

1. 多個條件的判斷

當我們需要進行多個值的判斷時,我們可以使用陣列的includes方法。

//Bad
if (x === 'iphoneX' || x === 'iphone11' || x === 'iphone12') {
//code... 
}
//Good
if (['iphoneX', 'iphone11', 'iphone12'].includes(x)) {
//code...
}

2. If true … else

#當if-else條件的內部不包含更大的邏輯時,三目運算符會更好。

// Bad
let test= boolean;
if (x > 100) {
test = true;
} else {
test = false;
}
// Good
let test = (x > 10) ? true : false;
//or we can simply use
let test = x > 10;

巢狀條件後,我們保留如下所示的內容(複雜點的三目):

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

3. Null、Undefined、'' 空值檢查

有時要檢查我們為值所引用的變數是否不為null或Undefined 或'' ,我們可以使用短路寫法

// Bad
if (first !== null || first !== undefined || first !== &#39;&#39;) {
let second = first;
}
// Good 短路写法
let second = first|| &#39;&#39;;

# 4. 空值檢查與分配預設值

當我們賦值,發現變數為空需要指派預設值可以使用以下短路寫法

let first = null,
let second = first || &#39;default&#39;
console.log(second)

4. 雙位運算子

位元運算子是JavaScript 初級教學的基本知識點,但是我們卻不常使用位元運算子。因為在不處理二進位的情況下,沒有人願意使用 1 和 0。

但是雙位運算子卻有一個很實用的案例。你可以使用雙位運算子來取代 Math.floor( )。雙重否定位元操作符的優點在於它執行相同的操作運行速度更快

// Bad
Math.floor(4.9) === 4  //true
// Good
~~4.9 === 4  //true

#5.ES6常見小優化- 物件屬性

const x,y = 5
// Bad
const obj = { x:x, y:y }
// Good
const obj = { x, y }

6. ES6常見小優化-箭頭函數

//Bad
function sayHello(name) {
  console.log(&#39;Hello&#39;, name);
}
setTimeout(function() {
  console.log(&#39;Loaded&#39;)
}, 2000)
list.forEach(function(item) {
  console.log(item)
})
// Good
const sayHello = name => console.log(&#39;Hello&#39;, name)
setTimeout(() => console.log(&#39;Loaded&#39;), 2000)
list.forEach(item => console.log(item))

7.ES6常見小最佳化-隱含回傳值

傳回值是我們通常用來傳回函數最終結果的關鍵字。只有一個語句的箭頭函數,可以隱式傳回結果(函數必須省略括號({ }),以便省略回傳關鍵字)。

要傳回多行語句(例如物件文字),需要使用()而不是{ }來包裹函數體。這樣可以確保程式碼以單一語句的形式進行求值。

//Bad
function calcCircumference(diameter) {
  return Math.PI * diameter
}
// Good
const calcCircumference = diameter => (
  Math.PI * diameter
)

8. ES6常見小最佳化-解構賦值

const form = { a:1, b:2, c:3 }
//Bad
const a = form.a
const b = form.b
const c = form.c
// Good
const { a, b, c } = form

9.ES6常見小最佳化-展開運算符

傳回值是我們通常用來傳回函數最終結果的關鍵字。只有一個語句的箭頭函數,可以隱式傳回結果(函數必須省略括號({ }),以便省略回傳關鍵字)。

要傳回多行語句(例如物件文字),需要使用()而不是{ }來包裹函數體。這樣可以確保程式碼以單一語句的形式進行求值。

const odd = [ 1, 3, 5 ]
const arr = [ 1, 2, 3, 4 ]
// Bad
const nums = [ 2, 4, 6 ].concat(odd)
const arr2 = arr.slice( )
// Good
const nums = [2 ,4 , 6, ...odd]
const arr2 = [...arr]

10. 陣列常見處理

#掌握陣列常見方法,記在腦子裡,不要寫的時候再去看API了,這樣可以有效提升編碼效率,畢竟這些方法每天都在用

every some filter map forEach find findIndex reduce includes

const arr = [1,2,3]
//every 每一项都成立,才会返回true
console.log( arr.every(it => it>0 ) ) //true
//some 有一项都成了,就会返回true
console.log( arr.some(it => it>2 ) ) //true
//filter 过滤器
console.log( arr.filter(it => it===2 ) ) //[2]
//map 返回一个新数组
console.log( arr.map(it => it==={id:it} ) ) //[ {id:1},{id:2},{id:3} ]
//forEach 没有返回值
console.log( arr.forEach(it => it===console.log(it)) ) //undefined
//find 查找对应值 找到就立马返回符合要求的新数组
console.log( arr.find(it => it===it>2) ) //3
//findIndex 查找对应值 找到就立马返回符合要求新数组的下标
console.log( arr.findIndex(it => it===it>2) ) //2
//reduce 求和或者合并数组
console.log( arr.reduce((prev,cur) => prev+cur) ) //6
//includes 求和或者合并数组
console.log( arr.includes(1) ) //true
//数组去重
const arr1 = [1,2,3,3]
const removeRepeat = (arr) => [...new Set(arr1)]//[1,2,3]
//数组求最大值
Math.max(...arr)//3
Math.min(...arr)//1
//对象解构 这种情况也可以使用Object.assign代替
let defaultParams={
    pageSize:1,
    sort:1
}
//goods1
let reqParams={
    ...defaultParams,
    sort:2
}
//goods2
Object.assign( defaultParams, {sort:2} )
#11. 比較回傳

在return語句中使用比較可以將程式碼從5行減少到1行。

// Bad
let test
const checkReturn = () => {
    if (test !== undefined) {
        return test;
    } else {
        return callMe(&#39;test&#39;);
}
}
// Good
const checkReturn = () => {
return test || callMe(&#39;test&#39;);
}
12. 短函數呼叫

我們可以使用三元運算子來實作這類函數。

const test1 =() => {
  console.log(&#39;test1&#39;);
}
const test2 =() => {
  console.log(&#39;test2&#39;);
}
const test3 = 1;
if (test3 == 1) {
  test1()
} else {
  test2()
}
// Good
test3 === 1? test1():test2()
13.switch程式碼區塊(ifelse程式碼區塊)簡寫

我們可以將條件儲存在key-value物件中,然後可以根據條件使用。

// Bad
switch (data) {
  case 1:
    test1();
  break;
  case 2:
    test2();
  break;
  case 3:
    test();
  break;
  // And so on...
}
// Good
const data = {
  1: test1,
  2: test2,
  3: test
}
data[anything] && data[anything]()
// Bad
if (type === &#39;test1&#39;) {
  test1();
}
else if (type === &#39;test2&#39;) {
  test2();
}
else if (type === &#39;test3&#39;) {
  test3();
}
else if (type === &#39;test4&#39;) {
  test4();
} else {
  throw new Error(&#39;Invalid value &#39; + type);
}
// Good
const types = {
  test1: test1,
  test2: test2,
  test3: test3,
  test4: test4
};
const func = types[type];
(!func) && throw new Error(&#39;Invalid value &#39; + type); func();
14. 多行字串簡寫

#當我們在程式碼中處理多行字串時,可以這樣做:

// Bad
const data = &#39;abc abc abc abc abc abc\n\t&#39;
+ &#39;test test,test test test test\n\t&#39;
// Good
const data = `abc abc abc abc abc abc
         test test,test test test test`

15. Object.entries() Object.values() Object.keys()

Object.entries() 這個特性可以將一個物件轉換成一個物件數組。

Object.values()可以拿到物件value值

Object.keys()可以拿到物件key值

const data = { test1: &#39;abc&#39;, test2: &#39;cde&#39; }
const arr1 = Object.entries(data)
const arr2 = Object.values(data)
const arr3 = Object.keys(data)
/** arr1 Output:
[ 
    [ &#39;test1&#39;, &#39;abc&#39; ],
    [ &#39;test2&#39;, &#39;cde&#39; ],
]
**/
/** arr2 Output:
[&#39;abc&#39;, &#39;cde&#39;]
**/
/** arr3 Output:
[&#39;test1&#39;, &#39;test2&#39;]
**/
16. 多次重複一個字串

為了多次重複相同的字符,我們可以使用for循環並將它們添加到同一個循環中,如何簡寫呢?

//Bad 
let test = &#39;&#39;; 
for(let i = 0; i < 5; i ++) { 
  test += &#39;test,&#39;; 
} 
console.log(str);// test,test,test,test,test,
//good 
console.log(&#39;test,&#39;.repeat(5))
17. 冪的簡寫

#數學指數冪函數的good如下:

//Bad 
Math.pow(2,3)// 8
//good 
2**3 // 8

###### #18. 數字分隔符號############你現在只需使用_ 即可輕鬆分隔數字。這將使處理大量數據變得更加輕鬆。 ###
//old syntax
let number = 98234567
//new syntax
let number = 98_234_567
###如果你想使用JavaScript最新版本(ES2021/ES12)的最新功能,請檢查以下內容:###
  • 1.replaceAll():傳回一個新字串,其中所有符合的模式都被新的替換詞取代。

  • 2.Promise.any():需要一個可迭代的Promise對象,當一個Promise完成時,傳回一個有值的Promise。

  • 3.weakref:此物件持有對另一個物件的弱引用,不阻止該物件被垃圾收集。

  • 4.FinalizationRegistry:讓你在物件被垃圾回收時請求回呼。

  • 5.私有方法:方法與存取器的修飾符:私有方法可以用#宣告。

  • 6.邏輯運算子:&&和||運算子。

  • 7.Intl.ListFormat:此物件啟用對語言敏感的清單格式。

  • 8.Intl.DateTimeFormat:此物件啟用對語言敏感的日期和時間格式。

【推薦學習:javascript進階教學

以上是18個你需要知道的JavaScript優化技巧的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:csdn.net。如有侵權,請聯絡admin@php.cn刪除