34 個 JavaScript 優(yōu)化技巧
原文地址:34 JavaScript Optimization Techniques to Know in 2021 原文作者:atit53 譯文出自:掘金翻譯計(jì)劃 本文永久鏈接:https://github.com/xitu/gold-miner/blob/master/article/2021/34-javascript-optimization-techniques-to-know-in-2021.md 譯者:samyu2000 校對者:Ashira97, PassionPenguin
2021 年需要了解的 34 個 JavaScript 優(yōu)化技巧
使用先進(jìn)的語法糖優(yōu)化你的 JavaScript 代碼
開發(fā)者需要持續(xù)學(xué)習(xí)新技術(shù),跟以前相比,如今跟隨技術(shù)變化是比較容易做到的,我寫這篇文章的目的是介紹諸如縮寫之類的 JavaScript 最佳實(shí)踐和其中的特性,這些都是我們作為一名前端開發(fā)人員必須了解的,因?yàn)樗鼤o我們的工作生活帶來便利。
可能你已經(jīng)進(jìn)行了多年的 JavaScript 開發(fā)工作,但有時候你還是會對一些最新的技術(shù)不那么了解,而這些新技術(shù)可能有助于某些問題的解決而不需要你去編寫更多的代碼。有時候,這些新技術(shù)也能幫助你進(jìn)行代碼優(yōu)化。此外,如果你今年需要為 JavaScript 面試作準(zhǔn)備,本文也是一份實(shí)用的參考資料。
在這里,我會介紹一些新的語法糖,它可以優(yōu)化你的 JavaScript 代碼,使代碼更簡潔。下面是一份 JavaScript 語法糖列表,你需要了解一下。
1. 含有多個條件的 if 語句
我們可以在數(shù)組中存儲多個值,并且可以使用數(shù)組的 includes 方法。
//longhand
if (x === 'abc' || x === 'def' || x === 'ghi' || x ==='jkl') {
//logic
}
//shorthand
if (['abc', 'def', 'ghi', 'jkl'].includes(x)) {
//logic
}
2. If … else 的縮寫法
當(dāng)我們的 if-else 條件中的邏輯比較簡單時,可以使用這種簡潔的方式——三元條件運(yùn)算符。
// 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"
3. 定義變量
當(dāng)我們定義兩個值相同或類型相同的變量,可以使用這樣的縮寫法
//Longhand
let test1;
let test2 = 1;
//Shorthand
let test1, test2 = 1;
4. 對 Null、Undefined、Empty 這些值的檢查
我們創(chuàng)建一個新變量,有時候需要檢查是否為 Null 或 Undefined。JavaScript 本身就有一種縮寫法能實(shí)現(xiàn)這種功能。
// Longhand
if (test1 !== null || test1 !== undefined || test1 !== '') {
let test2 = test1;
}
// Shorthand
let test2 = test1 || '';
5. 對 Null 值的檢查以及默認(rèn)賦值
let test1 = null,
test2 = test1 || '';console.log("null check", test2); // output will be ""
6. 對 Undefined 值的檢查以及默認(rèn)賦值
let test1 = undefined,
test2 = test1 || '';console.log("undefined check", test2); // output will be ""
對正常值的檢查
let test1 = 'test',
test2 = test1 || '';console.log(test2); // output: 'test'
利好消息:關(guān)于第 4、5、6 條還可以使用 ?? 運(yùn)算符
聚合運(yùn)算符
**??**是聚合運(yùn)算符,如果左值為 null 或 undefined,就返回右值。默認(rèn)返回左值。
const test= null ?? 'default';
console.log(test);
// expected output: "default"const test1 = 0 ?? 2;
console.log(test1);
// expected output: 0
7. 同時為多個變量賦值
當(dāng)我們處理多個變量,并且需要對這些變量賦不同的值,這種縮寫法很有用。
//Longhand
let test1, test2, test3;
test1 = 1;
test2 = 2;
test3 = 3;
//Shorthand
let [test1, test2, test3] = [1, 2, 3];
8. 賦值運(yùn)算符縮寫法
編程中使用算術(shù)運(yùn)算符是很常見的情況。以下是 JavaScript 中賦值運(yùn)算符的應(yīng)用。
// Longhand
test1 = test1 + 1;
test2 = test2 - 1;
test3 = test3 * 20;
// Shorthand
test1++;
test2--;
test3 *= 20;
9. 判斷變量是否存在的縮寫法
這是普遍使用的縮寫法,但在這里應(yīng)當(dāng)提一下。
// Longhand
if (test1 === true) or if (test1 !== "") or if (test1 !== null)
// Shorthand
//it will check empty string,null and undefined too
if (test1)
注意:當(dāng) test1 為任何值時,程序都會執(zhí)行 if(test1){ } 內(nèi)的邏輯,這種寫法在判斷 NULL 或 undefined 值時普遍使用。
10. 用于多個條件的與(&&)運(yùn)算符
如果需要實(shí)現(xiàn)某個變量為 true 時調(diào)用一個函數(shù),可以使用 && 運(yùn)算符。
//Longhand
if (test1) {
callMethod();
} //Shorthand
test1 && callMethod();
11. foreach 循環(huán)縮寫法
這是循環(huán)結(jié)構(gòu)對應(yīng)的縮寫法。
// Longhand
for (var i = 0; i < testData.length; i++)
// Shorthand
for (let i in testData) or for (let i of testData)
Array for each variable
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. 比較結(jié)果的返回
在 return 語句中,我們也可以使用比較的語句。這樣,原來需要 5 行代碼才能實(shí)現(xiàn)的功能,現(xiàn)在只需要 1 行,大大減少了代碼量。
// Longhand
let test;function checkReturn() {
if (!(test === undefined)) {
return test;
} else {
return callMe('test');
}
}
var data = checkReturn();
console.log(data); //output testfunction callMe(val) {
console.log(val);
}// Shorthandfunction checkReturn() {
return test || callMe('test');
}
13. 箭頭函數(shù)
//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. 簡短的函數(shù)調(diào)用語句
我們可以使用三元運(yùn)算符實(shí)現(xiàn)如下功能。
// 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 對應(yīng)的縮寫法
我們可以把條件值保存在名值對中,基于這個條件使用名值對代替 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]();
16. 隱式返回縮寫法
使用箭頭函數(shù),我們可以直接得到函數(shù)執(zhí)行結(jié)果,不需要寫 return 語句。
//longhand
function calculate(diameter) {
return Math.PI * diameter
}
//shorthand
calculate = diameter => (
Math.PI * diameter;
)
17. 十進(jìn)制數(shù)的指數(shù)形式
// Longhand
for (var i = 0; i < 10000; i++) { ... }
// Shorthand
for (var i = 0; i < 1e4; i++) {
18. 默認(rèn)參數(shù)值
//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
19. 延展操作符的縮寫法
//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];
20. 文本模板
如果你對使用 + 符號來連接多個變量感到厭煩,這個縮寫法可以幫到你。
//longhand
const welcome = 'Hi ' + test1 + ' ' + test2 + '.'
//shorthand
const welcome = `Hi ${test1} ${test2}`;
21. 跟多行文本有關(guān)的縮寫法
當(dāng)我們在代碼中處理多行文本時,可以使用這樣的技巧
//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. 字符串轉(zhuǎn)換為數(shù)字
//Longhand
let test1 = parseInt('123');
let test2 = parseFloat('12.3');
//Shorthand
let test1 = +'123';
let test2 = +'12.3';
24. 解構(gòu)賦值縮寫法
//longhand
const test1 = this.data.test1;
const test2 = this.data.test2;
const test2 = this.data.test3;
//shorthand
const { test1, test2, test3 } = this.data;
25. Array.find 縮寫法
當(dāng)我們需要在一個對象數(shù)組中按屬性值查找特定對象時,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. 查詢條件縮寫法
如果我們要檢查類型,并根據(jù)類型調(diào)用不同的函數(shù),我們既可以使用多個 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 縮寫法
我們以查找特定值為目的迭代一個數(shù)組,通常用到 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
}
對除 -1 外的任何數(shù)進(jìn)行 按位非(~) 運(yùn)算都會返回真值。把按位非的結(jié)果再次進(jìn)行邏輯取反就是 !~,這非常簡單。或者我們也可以使用 includes() 函數(shù):
if (arr.includes(item)) {
// true if the item found
}
28. Object.entries()
該特性可以把對象轉(zhuǎn)換成一個由若干對象組成的數(shù)組。
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. 兩個位運(yùn)算符縮寫
(兩個按位非運(yùn)算符只適用于 32 位整型)
// Longhand
Math.floor(1.9) === 1 // true
// Shorthand
~~1.9 === 1 // true
31. 把一個字符串重復(fù)多次
我們可以使用 for 循環(huán)把一個字符串反復(fù)輸出多次,那這種功能有沒有縮寫法呢?
//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. 找出一個數(shù)組中最大和最小的值
const arr = [1, 2, 3];
Math.max(…arr); // 3
Math.min(…arr); // 1
33. 獲取字符串中的字符
let str = 'abc';
//Longhand
str.charAt(2); // c
//Shorthand
//注意:如果事先知道目標(biāo)字符在字符串中的索引,我們可以直接使用該索引值。如果索引值不確定,運(yùn)行時就有可能拋出 undefined。
str[2]; // c
34. 冪運(yùn)算的縮寫法
指數(shù)冪函數(shù)的縮寫法:
//longhand
Math.pow(2,3); // 8
//shorthand
2**3 // 8
如果發(fā)現(xiàn)譯文存在錯誤或其他需要改進(jìn)的地方,歡迎到 掘金翻譯計(jì)劃 對譯文進(jìn)行修改并 PR,也可獲得相應(yīng)獎勵積分。文章開頭的 本文永久鏈接 即為本文在 GitHub 上的 MarkDown 鏈接。
