溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

JavaScript優(yōu)化技術(shù)都有哪些

發(fā)布時(shí)間:2021-09-30 11:14:20 來源:億速云 閱讀:143 作者:柒染 欄目:web開發(fā)

本篇文章為大家展示了JavaScript優(yōu)化技術(shù)都有哪些,內(nèi)容簡明扼要并且容易理解,絕對(duì)能使你眼前一亮,通過這篇文章的詳細(xì)介紹希望你能有所收獲。

開發(fā)人員的生活總是在學(xué)習(xí)新事物,并且跟上變化的難度不應(yīng)該比現(xiàn)在已經(jīng)難,我的動(dòng)機(jī)是介紹所有JavaScript最佳實(shí)踐,例如速記和功能,我們作為前端開發(fā)人員必須知道這些使我們的生活在2021年變得更加輕松。

您可能已經(jīng)進(jìn)行了很長時(shí)間的JavaScript開發(fā),但是有時(shí)您可能沒有使用不需要解決或編寫一些額外代碼即可解決問題的最新功能。這些技術(shù)可以幫助您編寫干凈且優(yōu)化的JavaScript代碼。此外,這些主題可以幫助您為2021年的JavaScript采訪做好準(zhǔn)備。

在這里,我將提供一個(gè)新系列,介紹速記技術(shù),這些速記技術(shù)可幫助您編寫更干凈和優(yōu)化的JavaScript代碼。

1.如果有多個(gè)條件

我們可以在數(shù)組中存儲(chǔ)多個(gè)值,并且可以使用數(shù)組include方法。

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

2.If true … else 簡寫

當(dāng)我們具有不包含更大邏輯的if-else條件時(shí),這是一個(gè)更大的捷徑。我們可以簡單地使用三元運(yùn)算符來實(shí)現(xià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);

當(dāng)我們有嵌套條件時(shí),我們可以采用這種方式。

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)我們要聲明兩個(gè)具有共同值或共同類型的變量時(shí),可以使用此簡寫形式。

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

4.空,未定義,空檢查

當(dāng)我們確實(shí)創(chuàng)建新變量時(shí),有時(shí)我們想檢查為其值引用的變量是否為null或未定義。JavaScript確實(shí)具有實(shí)現(xiàn)這些功能的非常好的捷徑。

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

5.空值檢查和分配默認(rèn)值

let test1 = null,     test2 = test1 || ''; console.log("null check", test2); // output will be ""

6.未定義值檢查和分配默認(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'

(獎(jiǎng)金:現(xiàn)在我們可以對(duì)主題4,5和6使用??運(yùn)算符)

空位合并運(yùn)算符

空合并運(yùn)算符??如果左側(cè)為null或未定義,則返回右側(cè)的值。默認(rèn)情況下,它將返回左側(cè)的值。

const test= null ?? 'default'; console.log(test); // expected output: "default"const test1 = 0 ?? 2; console.log(test1); // expected output: 0

7.給多個(gè)變量賦值

當(dāng)我們處理多個(gè)變量并希望將不同的值分配給不同的變量時(shí),此速記技術(shù)非常有用。

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

8.賦值運(yùn)算符的簡寫

我們?cè)诰幊讨刑幚砗芏嗨阈g(shù)運(yùn)算符。這是將運(yùn)算符分配給JavaScript變量的有用技術(shù)之一。

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

9.如果存在速記

這是我們大家都在使用的常用速記之一,但仍然值得一提。

// Longhand if (test1 === true)  // Shorthand if (test1)

注意:如果test1有任何值,它將在if循環(huán)后進(jìn)入邏輯,該運(yùn)算符通常用于null或未定義的檢查。

10.多個(gè)條件的AND(&&)運(yùn)算符

如果僅在變量為true的情況下才調(diào)用函數(shù),則可以使用&&運(yùn)算符。

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

11. foreach循環(huán)速記

這是迭代的常用速記技術(shù)之一。

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

每個(gè)變量的數(shù)組

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.箭頭函數(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速記

我們可以將條件保存在鍵值對(duì)象中,并可以根據(jù)條件使用。

// 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.隱式返回速記

使用箭頭功能,我們可以直接返回值,而不必編寫return語句。

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

17.小數(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.點(diǎn)差運(yùn)算符速記

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

對(duì)于克隆,我們也可以使用傳播運(yùn)算符。

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

20.模板文字

如果您厭倦了在單個(gè)字符串中使用+來連接多個(gè)變量,那么這種速記方式將消除您的頭痛。

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

21.多行字符串速記

當(dāng)我們?cè)诖a中處理多行字符串時(shí),可以使用以下功能:

//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.對(duì)象屬性分配

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

23.字符串成數(shù)字

//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. Array.find的簡寫

當(dāng)我們確實(shí)有一個(gè)對(duì)象數(shù)組并且我們想要根據(jù)對(duì)象屬性查找特定對(duì)象時(shí),find方法確實(shí)很有用。

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.查找條件速記

如果我們有代碼來檢查類型,并且基于類型需要調(diào)用不同的方法,我們可以選擇使用多個(gè)else if或進(jìn)行切換,但是如果我們的速記比這更好呢?

// 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.速記按位索引

當(dāng)我們迭代數(shù)組以查找特定值時(shí),我們確實(shí)使用indexOf()方法,如果我們找到更好的方法呢?讓我們看看這個(gè)例子。

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

按位(?)運(yùn)算符將返回非-1的真實(shí)值。取反就像做!?一樣簡單。另外,我們也可以使用include()函數(shù):

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

28. Object.entries()

此功能有助于將對(duì)象轉(zhuǎn)換為對(duì)象數(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中引入的一項(xiàng)新功能,它執(zhí)行與Object.entries()類似的功能,但沒有關(guān)鍵部分:

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

30. Double Bitwise簡寫

(雙重NOT按位運(yùn)算符方法僅適用于32位整數(shù))

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

31.重復(fù)一個(gè)字符串多次

要一次又一次地重復(fù)相同的字符,我們可以使用for循環(huán)并將它們添加到同一循環(huán)中,但是如果我們有一個(gè)簡寫方法呢?

//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(&hellip;arr); // 3 Math.min(&hellip;arr); // 1

33.從字符串中獲取字符

let str = 'abc'; //Longhand  str.charAt(2); // c //Shorthand  Note: 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 undefined str[2]; // c

34.功率速記

數(shù)學(xué)指數(shù)冪函數(shù)的簡寫:

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

上述內(nèi)容就是JavaScript優(yōu)化技術(shù)都有哪些,你們學(xué)到知識(shí)或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識(shí)儲(chǔ)備,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI