34種你需要了解的JavaScript優(yōu)化技術

文末送《Web前端性能優(yōu)化》書籍
希望你堅持看完并帶走彩蛋
英文 | https://javascript.plainenglish.io/34-javascript-optimization-techniques-to-know-in-2021-d561afdf73c3
翻譯 | https://www.dsiab.com/post/3922
1、如果有多個條件
我們可以在數組中存儲多個值,并且可以使用數組include方法。
//longhandif (x === 'abc' || x === 'def' || x === 'ghi' || x ==='jkl') {//logic}//shorthandif (['abc', 'def', 'ghi', 'jkl'].includes(x)) {//logic}
2、If true … else 簡寫
當我們具有不包含更大邏輯的if-else條件時,這是一個更大的捷徑。我們可以簡單地使用三元運算符來實現該速記。
// Longhandlet test: boolean;if (x > 100) {test = true;} else {test = false;}// Shorthandlet test = (x > 10) ? true : false;//or we can use directlylet 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、聲明變量
當我們要聲明兩個具有共同值或共同類型的變量時,可以使用此簡寫形式。
//Longhandlet test1;let test2 = 1;//Shorthandlet test1, test2 = 1;
4、空,未定義,空檢查
當我們確實創(chuàng)建新變量時,有時我們想檢查為其值引用的變量是否為null或未定義。JavaScript確實具有實現這些功能的非常好的捷徑。
// Longhandif (test1 !== null || test1 !== undefined || test1 !== '') {let test2 = test1;}// Shorthandlet test2 = test1 || '';
5、空值檢查和分配默認值
let test1 = null,test2 = test1 || '';console.log("null check", test2); // output will be ""
6、未定義值檢查和分配默認值
let test1 = undefined,test2 = test1 || '';console.log("undefined check", test2); // output will be ""
正常值檢查
let test1 = 'test',test2 = test1 || '';console.log(test2); // output: 'test'
空位合并運算符
空合并運算符??如果左側為null或未定義,則返回右側的值。默認情況下,它將返回左側的值。
const test= null ?? 'default';console.log(test);// expected output: "default"const test1 = 0 ?? 2;console.log(test1);// expected output: 0
7、給多個變量賦值
當我們處理多個變量并希望將不同的值分配給不同的變量時,此速記技術非常有用。
//Longhandlet test1, test2, test3;test1 = 1;test2 = 2;test3 = 3;//Shorthandlet [test1, test2, test3] = [1, 2, 3];
8、賦值運算符的簡寫
我們在編程中處理很多算術運算符。這是將運算符分配給JavaScript變量的有用技術之一。
// Longhandtest1 = test1 + 1;test2 = test2 - 1;test3 = test3 * 20;// Shorthandtest1++;test2--;test3 *= 20;
9、如果存在速記
這是我們大家都在使用的常用速記之一,但仍然值得一提。
// Longhandif (test1 === true)// Shorthandif (test1)
注意:如果test1有任何值,它將在if循環(huán)后進入邏輯,該運算符通常用于null或未定義的檢查。
10、多個條件的AND(&&)運算符
如果僅在變量為true的情況下才調用函數,則可以使用&&運算符。
//Longhandif (test1) {callMethod();}//Shorthandtest1 && callMethod();
11、foreach循環(huán)速記
這是迭代的常用速記技術之一。
// Longhandfor (var i = 0; i < testData.length; i++)// Shorthandfor (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行。
// Longhandlet 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、箭頭函數
//Longhandfunction add(a, b) {return a + b;}//Shorthandconst add = (a, b) => a + b;
更多示例。
function callMe(name) {console.log('Hello', name);}callMe = name => console.log('Hello', name);
14、短函數調用
我們可以使用三元運算符來實現這些功能。
// Longhandfunction 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速記
我們可以將條件保存在鍵值對象中,并可以根據條件使用。
// Longhandswitch (data) {case 1:test1();break;case 2:test2();break;case 3:test();break;// And so on...}// Shorthandvar data = {1: test1,2: test2,3: test};data[something] && data[something]();
16、隱式返回速記
使用箭頭功能,我們可以直接返回值,而不必編寫return語句。
//longhandfunction calculate(diameter) {return Math.PI * diameter}//shorthandcalculate = diameter => (Math.PI * diameter;)
17、小數基指數
// Longhandfor (var i = 0; i < 10000; i++) { ... }// Shorthandfor (var i = 0; i < 1e4; i++) {
18、默認參數值
//Longhandfunction add(test1, test2) {if (test1 === undefined)test1 = 1;if (test2 === undefined)test2 = 2;return test1 + test2;}//shorthandadd = (test1 = 1, test2 = 2) => (test1 + test2);add() //output: 3
19、點差運算符速記
//longhand// joining arrays using concatconst data = [1, 2, 3];const test = [4 ,5 , 6].concat(data);//shorthand// joining arraysconst data = [1, 2, 3];const test = [4 ,5 , 6, ...data];console.log(test); // [ 4, 5, 6, 1, 2, 3]
對于克隆,我們也可以使用傳播運算符。
//longhand// cloning arraysconst test1 = [1, 2, 3];const test2 = test1.slice()//shorthand// cloning arraysconst test1 = [1, 2, 3];const test2 = [...test1];
20、模板文字
如果您厭倦了在單個字符串中使用+來連接多個變量,那么這種速記方式將消除您的頭痛。
//longhandconst welcome = 'Hi ' + test1 + ' ' + test2 + '.'//shorthandconst welcome = `Hi ${test1} ${test2}`;
21、多行字符串速記
當我們在代碼中處理多行字符串時,可以使用以下功能:
//longhandconst data = 'abc abc abc abc abc abc\n\t'+ 'test test,test test test test\n\t'//shorthandconst data = `abc abc abc abc abc abctest test,test test test test`
22、對象屬性分配
let test1 = 'a';let test2 = 'b';//Longhandlet obj = {test1: test1, test2: test2};//Shorthandlet obj = {test1, test2};
23、字符串成數字
//Longhandlet test1 = parseInt('123');let test2 = parseFloat('12.3');//Shorthandlet test1 = +'123';let test2 = +'12.3';
24、分配速記
//longhandconst test1 = this.data.test1;const test2 = this.data.test2;const test2 = this.data.test3;//shorthandconst { test1, test2, test3 } = this.data;
25、 Array.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];}}}//ShorthandfilteredData = data.find(data => data.type === 'test1' && data.name === 'fgh');console.log(filteredData); // { type: 'test1', name: 'fgh' }
26、查找條件速記
如果我們有代碼來檢查類型,并且基于類型需要調用不同的方法,我們可以選擇使用多個else if或進行切換,但是如果我們的速記比這更好呢?
// Longhandif (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);}// Shorthandvar types = {test1: test1,test2: test2,test3: test3,test4: test4};var func = types[type];(!func) && throw new Error('Invalid value ' + type); func();
27、速記按位索引
當我們迭代數組以查找特定值時,我們確實使用indexOf()方法,如果我們找到更好的方法呢?讓我們看看這個例子。
//longhandif(arr.indexOf(item) > -1) { // item found}if(arr.indexOf(item) === -1) { // item not found}//shorthandif(~arr.indexOf(item)) { // item found}if(!~arr.indexOf(item)) { // item not found}
按位(?)運算符將返回非-1的真實值。取反就像做!?一樣簡單。另外,我們也可以使用include()函數:
if (arr.includes(item)) {// true if the item found}
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中引入的一項新功能,它執(zhí)行與Object.entries()類似的功能,但沒有關鍵部分:
const data = { test1: 'abc', test2: 'cde' };const arr = Object.values(data);console.log(arr);/** Output:[ 'abc', 'cde']**/
30、Double Bitwise簡寫
(雙重NOT按位運算符方法僅適用于32位整數)
// LonghandMath.floor(1.9) === 1 // true// Shorthand~~1.9 === 1 // true
31、重復一個字符串多次
要一次又一次地重復相同的字符,我們可以使用for循環(huán)并將它們添加到同一循環(huán)中,但是如果我們有一個簡寫方法呢?
//longhandlet 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); // 3Math.min(…arr); // 1
33、從字符串中獲取字符
let str = 'abc';//Longhandstr.charAt(2); // c//ShorthandNote: If we know the index of the array then we can directly use index insted of character.If we are not sure about index it can throw undefinedstr[2]; // c
34、功率速記
//longhandMath.pow(2,3); // 8//shorthand2**3 // 8
福利時間
最后,我又來給大家送福利了,這么好的書不送幾本給大家怎么行呢?

只要項目還在用,前端性能就永遠是時刻要關注的問題,閱讀本書掌握前端系統、實用、專業(yè)的性能優(yōu)化解決方案。
構筑前端性能知識體系,將零散知識點聚沙成塔,理清脈絡
針對6大優(yōu)化場景,層層剝繭式分析,讓讀者知其然也知其所以然
沉淀作者5年一線大廠開發(fā)經驗,逐個性能點解析實踐場景
匯集12年專業(yè)知識,帶你全面理解關乎性能的前因后果
這次準備了2種方式抽獎,「評論點贊、朋友圈點贊」這兩種方式都可以參與!感謝親愛的讀者們,你們的支持也是我持續(xù)更文最大的動力。
本次開獎時間為 2021.4.18 22:00
為了避免中獎后失聯,提前加我微信哈
留言點贊(2本)
留言點贊數「第一、二名」可獲得一本
《Web前端性能優(yōu)化》
PS:買點贊數等作弊無效,一切解釋權歸前端Q所有
朋友圈點贊抽獎(2本)
記得先添加我微信,不然我看不到哪些小伙伴點贊
大獎:本文章我會轉發(fā)朋友圈,給第n位(具體數值看朋友圈發(fā)布時的規(guī)則)點贊朋友圈的同學送出一本
《Web前端性能優(yōu)化》,共2位幸運兒。參與獎:朋友圈點贊者中給第n位(具體數值看朋友圈發(fā)布時的規(guī)則)送出「5.2元」紅包,共5位幸運兒。
最后
歡迎加我微信(winty230),拉你進技術群,長期交流學習...
歡迎關注「前端Q」,認真學前端,做個專業(yè)的技術人...


