<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          2021年不可錯(cuò)過(guò)的34種JS優(yōu)化技巧

          共 8168字,需瀏覽 17分鐘

           ·

          2021-06-18 05:37

          作者丨 Atit
          譯者丨王者
          轉(zhuǎn)載丨前端之巔
          開(kāi)發(fā)者總是在學(xué)習(xí)新東西,而跟上這些技術(shù)的變化不應(yīng)該比之前更難。我寫(xiě)這篇文章的目的是介紹 JavaScript 的一些最佳實(shí)踐,作為前端開(kāi)發(fā)人員,掌握了這些最佳實(shí)踐會(huì)讓我們?cè)?2021 年的工作變得更輕松。

          你可能做了很長(zhǎng)時(shí)間的 JavaScript 開(kāi)發(fā),但有時(shí)候你可能沒(méi)有使用最新的 JavaScript 特性或技巧,這些特性和技巧可以在不需要編寫(xiě)額外代碼的情況下解決你的問(wèn)題。它們可以幫助你寫(xiě)出干凈且優(yōu)化的 JavaScript 代碼。此外,如果你在 2021 年準(zhǔn)備去參加面試,可以參考本文的內(nèi)容。

          1. 帶有多個(gè)條件的 if 語(yǔ)句


          把多個(gè)值放在一個(gè)數(shù)組中,然后調(diào)用數(shù)組的 includes 方法。

          //longhand
          if (x === 'abc' || x === 'def' || x === 'ghi' || x ==='jkl') {
          //logic
          }
          //shorthand
          if (['abc', 'def', 'ghi', 'jkl'].includes(x)) {
          //logic
          }
          2. 簡(jiǎn)化 if true...else


          對(duì)于不包含大邏輯的 if-else 條件,可以使用下面的快捷寫(xiě)法。我們可以簡(jiǎn)單地使用三元運(yùn)算符來(lái)實(shí)現(xiàn)這種簡(jiǎ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)我們想要聲明兩個(gè)具有相同的值或相同類型的變量時(shí),可以使用這種簡(jiǎn)寫(xiě)。

          //Longhand 
          let test1;
          let test2 = 1;
          //Shorthand
          let test1, test2 = 1;
          4. null、undefined 和空值檢查


          當(dāng)我們創(chuàng)建了新變量,有時(shí)候想要檢查引用的變量是不是為非 null 或 undefined。JavaScript 確實(shí)有一個(gè)很好的快捷方式來(lái)實(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'

          另外,對(duì)于上述的 4、5、6 點(diǎ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. 給多個(gè)變量賦值


          當(dāng)我們想給多個(gè)不同的變量賦值時(shí),這種技巧非常有用。

          //Longhand 
          let test1, test2, test3;
          test1 = 1;
          test2 = 2;
          test3 = 3;
          //Shorthand
          let [test1, test2, test3] = [1, 2, 3];
          8. 簡(jiǎn)便的賦值操作符


          在編程過(guò)程中,我們要處理大量的算術(shù)運(yùn)算符。這是 JavaScript 變量賦值操作符的有用技巧之一。

          // Longhand
          test1 = test1 + 1;
          test2 = test2 - 1;
          test3 = test3 * 20;
          // Shorthand
          test1++;
          test2--;
          test3 *= 20;
          9. if 判斷值是否存在


          這是我們都在使用的一種常用的簡(jiǎn)便技巧,在這里仍然值得再提一下。

          // Longhand
          if (test1 === true) or if (test1 !== "") or if (test1 !== null)
          // Shorthand //it will check empty string,null and undefined too
          if (test1)

          注意:如果 test1 有值,將執(zhí)行 if 之后的邏輯,這個(gè)操作符主要用于 null 或 undefinded 檢查。

          10. 用于多個(gè)條件判斷的 && 操作符


          如果只在變量為 true 時(shí)才調(diào)用函數(shù),可以使用 && 操作符。

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


          11. for each 循環(huán)


          這是一種常見(jiàn)的循環(huán)簡(jiǎn)化技巧。

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

          遍歷數(shù)組的每一個(gè)變量。

          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 語(yǔ)句中使用比較,它可以將 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. 簡(jiǎn)短的函數(shù)調(diào)用


          我們可以使用三元操作符來(lái)實(shí)現(xiàn)多個(gè)函數(shù)調(diào)用。

          // 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 簡(jiǎn)化


          我們可以將條件保存在鍵值對(duì)象中,并根據(jù)條件來(lái)調(diào)用它們。

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


          通過(guò)使用箭頭函數(shù),我們可以直接返回值,不需要 return 語(yǔ)句。

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


          17. 指數(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. 延展操作符簡(jiǎ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]

          我們也可以使用延展操作符進(jì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è)字符串,那么這個(gè)簡(jiǎn)化技巧將讓你不再頭痛。

          //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. 將字符串轉(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. 數(shù)組 find 簡(jiǎn)化


          當(dāng)我們有一個(gè)對(duì)象數(shù)組,并想根據(jù)對(duì)象屬性找到特定對(duì)象,find 方法會(huì)非常有用。

          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. 條件查找簡(jiǎn)化


          如果我們要基于不同的類型調(diào)用不同的方法,可以使用多個(gè) else if 語(yǔ)句或 switch,但有沒(méi)有比這更好的簡(jiǎ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. indexOf 的按位操作簡(jiǎn)化


          在查找數(shù)組的某個(gè)值時(shí),我們可以使用 indexOf() 方法。但有一種更好的方法,讓我們來(lái)看一下這個(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)算符將返回 true(-1 除外),反向操作只需要!~。另外,也可以使用 include() 函數(shù)。

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


          28. Object.entries()


          這個(gè)方法可以將對(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 中引入的一個(gè)新特性,它的功能類似于 Object.entries(),只是沒(méi)有鍵。

          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. 重復(fù)字符串多次


          為了重復(fù)操作相同的字符,我們可以使用 for 循環(huán),但其實(shí)還有一種簡(jiǎn)便的方法。

          //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
          str[2]; // c


          34. 指數(shù)冪簡(jiǎn)化


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

          原文鏈接:

          https://javascript.plainenglish.io/34-javascript-optimization-techniques-to-know-in-2021-d561afdf73c3


          瀏覽 25
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          評(píng)論
          圖片
          表情
          推薦
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  日韩黄色影视 | 久久久久久久久久免费看视频 | 越南无码在线 | 五月激情成人 | 日本成人一级性片在线观看 |