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

          大佬說(shuō):“不想加班你就背會(huì)這 10 條 JS 技巧”

          共 10670字,需瀏覽 22分鐘

           ·

          2021-02-28 19:51

          • 作者:陳大魚頭
          • github:KRISACHAN

          為了讓自己寫的代碼更優(yōu)雅且高效,特意向大佬請(qǐng)教了這 10 條 JS 技巧

          1. 數(shù)組分割

          const listChunk = (list = [], chunkSize = 1) => {
              const result = [];
              const tmp = [...list];
              if (!Array.isArray(list) || !Number.isInteger(chunkSize) || chunkSize <= 0) {
                  return result;
              };
              while (tmp.length) {
                  result.push(tmp.splice(0, chunkSize));
              };
              return result;
          };
          listChunk(['a''b''c''d''e''f''g']);
          // [['a'], ['b'], ['c'], ['d'], ['e'], ['f'], ['g']]

          listChunk(['a''b''c''d''e''f''g'], 3);
          // [['a', 'b', 'c'], ['d', 'e', 'f'], ['g']]

          listChunk(['a''b''c''d''e''f''g'], 0);
          // []

          listChunk(['a''b''c''d''e''f''g'], -1);
          // []

          2. 求數(shù)組元素交集

          const listIntersection = (firstList, ...args) => {
              if (!Array.isArray(firstList) || !args.length) {
                  return firstList;
              }
              return firstList.filter(item => args.every(list => list.includes(item)));
          };
          listIntersection([12], [34]);
          // []

          listIntersection([22], [34]);
          // []

          listIntersection([32], [34]);
          // [3]

          listIntersection([34], [34]);
          // [3, 4]

          3. 按下標(biāo)重新組合數(shù)組

          const zip = (firstList, ...args) => {
              if (!Array.isArray(firstList) || !args.length) {
                  return firstList
              };
              return firstList.map((value, index) => {
                  const newArgs = args.map(arg => arg[index]).filter(arg => arg !== undefined);
                  const newList = [value, ...newArgs];
                  return newList;
              });
          };
          zip(['a''b'], [12], [truefalse]);
          // [['a', 1, true], ['b', 2, false]]

          zip(['a''b''c'], [12], [truefalse]);
          // [['a', 1, true], ['b', 2, false], ['c']]

          4. 按下標(biāo)組合數(shù)組為對(duì)象

          const zipObject = (keys, values = {}) => {
              const emptyObject = Object.create({});
              if (!Array.isArray(keys)) {
                  return emptyObject;
              };
              return keys.reduce((acc, cur, index) => {
                  acc[cur] = values[index];
                  return acc;
              }, emptyObject);
          };
          zipObject(['a''b'], [12])
          // { a: 1, b: 2 }
          zipObject(['a''b'])
          // { a: undefined, b: undefined }

          5. 檢查對(duì)象屬性的值

          const checkValue = (obj = {}, objRule = {}) => {
              const isObject = obj => {
                  return Object.prototype.toString.call(obj) === '[object Object]';
              };
              if (!isObject(obj) || !isObject(objRule)) {
                  return false;
              }
              return Object.keys(objRule).every(key => objRule[key](obj[key]));
          };

          const object = { a1b2 };

          checkValue(object, {
              bn => n > 1,
          })
          // true

          checkValue(object, {
              bn => n > 2,
          })
          // false

          6. 獲取對(duì)象屬性

          const get = (obj, path, defaultValue) => {
              if (!path) {
                  return;
              };
              const pathGroup = Array.isArray(path) ? path : path.match(/([^[.\]])+/g);
              return pathGroup.reduce((prevObj, curKey) => prevObj && prevObj[curKey], obj) || defaultValue;
          };

          const obj1 = { a: { b2 } }
          const obj2 = { a: [{ bar: { c3 } }] }

          get(obj1, 'a.b')
          // 2
          get(obj2, 'a[0].bar.c')
          // 3
          get(obj2, ['a', '0', 'bar', 'c'])
          // 2
          get(obj1, 'a.bar.c', 'default')
          // default
          get(obj1, 'a.bar.c', 'default')
          // default

          7. 將特殊符號(hào)轉(zhuǎn)成字體符號(hào)

          const escape = str => {
              const isString = str => {
                  return Object.prototype.toString.call(str) === '[string Object]';
              };
              if (!isString(str)) {
                  return str;
              }
              return (str.replace(/&/g'&amp;')
                .replace(/"/g'&quot;')
                .replace(/'/g'&#x27;')
                .replace(/</g'&lt;')
                .replace(/>/g'&gt;')
                .replace(/\//g'&#x2F;')
                .replace(/\\/g'&#x5C;')
                .replace(/`/g'&#96;'));
          };

          8. 利用注釋創(chuàng)建一個(gè)事件監(jiān)聽(tīng)器

          class EventEmitter {
              #eventTarget;
              constructor(content = '') {
                  const comment = document.createComment(content);
                  document.documentElement.appendChild(comment);
                  this.#eventTarget = comment;
              }
              on(type, listener) {
                  this.#eventTarget.addEventListener(type, listener);
              }
              off(type, listener) {
                  this.#eventTarget.removeEventListener(type, listener);
              }
              once(type, listener) {
                  this.#eventTarget.addEventListener(type, listener, { oncetrue });
              }
              emit(type, detail) {
                  const dispatchEvent = new CustomEvent(type, { detail });
                  this.#eventTarget.dispatchEvent(dispatchEvent);
              }
          };

          const emmiter = new EventEmitter();
          emmiter.on('biy', () => {
              console.log('hello world');
          });
          emmiter.emit('biu');
          // hello world

          9. 生成隨機(jī)的字符串

          const genRandomStr = (len = 1) => {
              let result = '';
              for (let i = 0; i < len; ++i) {
                  result += Math.random().toString(36).substr(2)
              }
              return result.substr(0, len);
          }
          genRandomStr(3)
          // u2d
          genRandomStr()
          // y
          genRandomStr(10)
          // qdueun65jb

          10. 判斷是否是指定的哈希值

          const isHash = (type = '', str = '') => {
              const isString = str => {
                  return Object.prototype.toString.call(str) === '[string Object]';
              };
              if (!isString(type) || !isString(str)) {
                  return str;
              };
              const algorithms = {
                  md532,
                  md432,
                  sha140,
                  sha25664,
                  sha38496,
                  sha512128,
                  ripemd12832,
                  ripemd16040,
                  tiger12832,
                  tiger16040,
                  tiger19248,
                  crc328,
                  crc32b8,
              };
              const hash = new RegExp(`^[a-fA-F0-9]{${algorithms[type]}}$`);
              return hash.test(str);
          };

          isHash('md5''d94f3f016ae679c3008de268209132f2');
          // true
          isHash('md5''q94375dj93458w34');
          // false

          isHash('sha1''3ca25ae354e192b26879f651a51d92aa8a34d8d3');
          // true
          isHash('sha1''KYT0bf1c35032a71a14c2f719e5a14c1');
          // false
          瀏覽 29
          點(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>
                  手机在线永久免费观看AV片 | 久操视频中文在线 | 青青草2017在线视频 | 天堂网2020 | 强开小嫩苞一区二区三区图片 |