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

          58個(gè)面向 Web 開發(fā)人員的JavaScript技巧匯總

          共 8707字,需瀏覽 18分鐘

           ·

          2022-04-18 19:16

          來(lái)源 | https://blog.bitsrc.io/common-js-development-skills-5053f0a74ced


          作為程序員,編寫代碼也需要大量的技巧。好的代碼可以讓人耳目一新、通俗易懂、舒適自然,同時(shí)又充滿成就感。

          因此,整理了一些近三年,我使用過(guò)的JavaScript開發(fā)技巧,希望能讓大家寫出耳目一新、通俗易懂、舒適自然的代碼。

          字符串技巧

          1、比較時(shí)間

          const time1 = "2022-03-02 09:00:00";const time2 = "2022-03-02 09:00:01";const overtime = time1 < time2;// overtime => true

          2、格式化money

          const ThousandNum = num => num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");const money = ThousandNum(1000000);// money => '1,000,000'

          3、生成隨機(jī)ID

          const RandomId = len => Math.random().toString(36).substr(3, len);const id = RandomId(10);// id => "xdeguewg1f"

          4、生成隨機(jī) HEX 顏色值

          const RandomColor = () => "#" + Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0");const color = RandomColor();// color => "#2cbf89"

          5、Generate star ratings

          const StartScore = rate => "★★★★★☆☆☆☆☆".slice(5 - rate, 10 - rate);const start = StartScore(3);// start => '★★★☆☆'

          6、網(wǎng)址查詢參數(shù)

          const params = new URLSearchParams(location.search.replace(/\?/ig, "")); // location.search = "?name=test&sex=man"params.has("test"); // trueparams.get("sex"); // "man"

          數(shù)字技能

          7、Arrangement

          用 Math.floor() 代替正數(shù),用 Math.ceil() 代替負(fù)數(shù)

          const num1 = ~~ 1.19;const num2 = 2.29 | 0;const num3 = 3.09 >> 0;// num1 num2 num3 => 1 2 3

          8、零填充

          const FillZero = (num, len) => num.toString().padStart(len, "0");const num = FillZero(1234, 5);// num => "01234"

          9、轉(zhuǎn)數(shù)

          僅對(duì) null、“”、false、數(shù)字字符串有效

          const num1 = +null;const num2 = +"";const num3 = +false;const num4 = +"169";// num1 num2 num3 num4 => 0 0 0 169

          10、時(shí)間戳

          const timestamp = +new Date("2022-03-22");// timestamp => 1647907200000

          11、精確小數(shù)

          const RoundNum = (num, decimal) => Math.round(num * 10 ** decimal) / 10 ** decimal;const num = RoundNum(1.2345, 2);// num => 1.23

          12、平價(jià)

          const OddEven = num => !!(num & 1) ? "odd" : "even";const num = OddEven(2);// num => "even"

          13、取最小值最大值

          const arr = [0, 1, 2, 3];const min = Math.min(...arr);const max = Math.max(...arr);// min max => 0 3

          14、生成范圍隨機(jī)數(shù)

          const RandomNum = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;const num = RandomNum(1, 10); // 5

          布爾技能

          15、短路運(yùn)算符

          const a = d && 1; // Fake operation, judge from left to right, return a false value when encountering a false value, and no longer execute it later, otherwise return the last true valueconst b = d || 1; // Take the true operation, judge from left to right, return the true value when encountering the true value, and do not execute it later, otherwise return the last false valueconst c = !d; // Returns false if a single expression converts to true, otherwise returns true

          16、確定數(shù)據(jù)類型

          可確定的類型:undefined、null、string、number、boolean、array、object、symbol、date、regexp、function、asyncfunction、arguments、set、map、weakset、weakmap

          function DataType(tgt, type) {    const dataType = Object.prototype.toString.call(tgt).replace(/\[object (\w+)\]/, "$1").toLowerCase();    return type ? dataType === type : dataType;}DataType("test"); // "string"DataType(20220314); // "number"DataType(true); // "boolean"DataType([], "array"); // trueDataType({}, "array"); // false

          17、檢查數(shù)組是否為空

          const arr = [];const flag = Array.isArray(arr) && !arr.length;// flag => true

          18、滿足條件時(shí)執(zhí)行

          const flagA = true; // Condition Aconst flagB = false; // Condition B(flagA || flagB) && Func(); // Execute when A or B is satisfied(flagA || !flagB) && Func(); // Execute when A is satisfied or B is not satisfiedflagA && flagB && Func(); // Execute when both A and B are satisfiedflagA && !flagB && Func(); // Execute when A is satisfied and B is not satisfied

          19、如果非假則執(zhí)行

          const flag = false; // undefined、null、""、0、false、NaN!flag && Func();

          20、數(shù)組不為空時(shí)執(zhí)行

          const arr = [0, 1, 2];arr.length && Func();

          21、對(duì)象不為空時(shí)執(zhí)行

          const obj = { a: 0, b: 1, c: 2 };Object.keys(obj).length && Func();

          陣列技能

          22、克隆數(shù)組

          const _arr = [0, 1, 2];const arr = [..._arr];// arr => [0, 1, 2]

          23、合并數(shù)組

          const arr1 = [0, 1, 2];const arr2 = [3, 4, 5];const arr = [...arr1, ...arr2];// arr => [0, 1, 2, 3, 4, 5];

          24、去重?cái)?shù)組

          const arr = [...new Set([0, 1, 1, null, null])];// arr => [0, 1, null]

          25、混淆數(shù)組

          const arr = [0, 1, 2, 3, 4, 5].slice().sort(() => Math.random() - .5);// arr => [3, 4, 0, 5, 1, 2]

          26、清空數(shù)組

          const arr = [0, 1, 2];arr.length = 0;// arr => []

          27、截?cái)鄶?shù)組

          const arr = [0, 1, 2];arr.length = 2;// arr => [0, 1]

          28、交換數(shù)值

          let a = 0;let b = 1;[a, b] = [b, a];// a b => 1 0

          29、過(guò)濾空值

          空值:undefined,null,””,0,false,NaN

          const arr = [undefined, null, "", 0, false, NaN, 1, 2].filter(Boolean);// arr => [1, 2]

          30、在數(shù)組開頭插入成員

          let arr = [1, 2];arr.unshift(0);arr = [0].concat(arr);arr = [0, ...arr];// arr => [0, 1, 2]

          31、在數(shù)組末尾插入元素

          let arr = [0, 1]; arr.push(2);arr.concat(2);arr[arr.length] = 2;arr = [...arr, 2];// arr => [0, 1, 2]

          32、計(jì)算數(shù)組成員的數(shù)量

          const arr = [0, 1, 1, 2, 2, 2];const count = arr.reduce((t, v) => { t[v] = t[v] ? ++t[v] : 1; return t;}, {});// count => { 0: 1, 1: 2, 2: 3 }

          33、解構(gòu)嵌套數(shù)組成員

          const arr = [0, 1, [2, 3, [4, 5]]];const [a, b, [c, d, [e, f]]] = arr;// a b c d e f => 0 1 2 3 4 5

          34、解構(gòu)數(shù)組成員別名

          const arr = [0, 1, 2];const { 0: a, 1: b, 2: c } = arr;// a b c => 0 1 2

          35、解構(gòu)數(shù)組成員默認(rèn)值

          const arr = [0, 1, 2];const [a, b, c = 3, d = 4] = arr;// a b c d => 0 1 2 4

          36、獲取隨機(jī)數(shù)組成員

          const arr = [0, 1, 2, 3, 4, 5];const randomItem = arr[Math.floor(Math.random() * arr.length)];// randomItem => 1

          37、創(chuàng)建指定長(zhǎng)度的數(shù)組

          const arr = [...new Array(3).keys()];// arr => [0, 1, 2]

          38、創(chuàng)建一個(gè)指定長(zhǎng)度和相等值的數(shù)組

          const arr = new Array(3).fill(0);// arr => [0, 0, 0]

          對(duì)象技能

          39、克隆對(duì)象

          const _obj = { a: 0, b: 1, c: 2 };const obj = { ..._obj };const obj = JSON.parse(JSON.stringify(_obj));// obj => { a: 0, b: 1, c: 2 }

          40、合并對(duì)象

          const obj1 = { a: 0, b: 1, c: 2 };const obj2 = { c: 3, d: 4, e: 5 };const obj = { ...obj1, ...obj2 };// obj => { a: 0, b: 1, c: 3, d: 4, e: 5 }

          41、對(duì)象變量屬性

          const flag = false;const obj = {    a: 0,    b: 1,    [flag ? "c" : "d"]: 2};// obj => { a: 0, b: 1, d: 2 }

          42、創(chuàng)建一個(gè)純空對(duì)象

          const obj = Object.create(null);Object.prototype.a = 0;// obj => {}

          43、刪除對(duì)象無(wú)用屬性

          const obj = { a: 0, b: 1, c: 2 }; const { a, ...rest } = obj;// rest => { b: 1, c: 2 }

          44、解構(gòu)對(duì)象屬性嵌套

          const obj = { a: 0, b: 1, c: { d: 2, e: 3 } };const { c: { d, e } } = obj;// d e => 2 3

          45、解構(gòu)對(duì)象屬性別名

          const obj = { a: 0, b: 1, c: 2 };const { a, b: d, c: e } = obj;// a d e => 0 1 2

          46、解構(gòu)對(duì)象屬性默認(rèn)值

          const obj = { a: 0, b: 1, c: 2 };const { a, b = 2, d = 3 } = obj;// a b d => 0 1 3

          函數(shù)技能

          47、函數(shù)自執(zhí)行

          const Func = function() {}(); // Commonly used(function() {})(); // Commonly used(function() {}()); // Commonly used[function() {}()];+ function() {}();- function() {}();~ function() {}();! function() {}();new function() {};new function() {}();void function() {}();typeof function() {}();delete function() {}();1, function() {}();1 ^ function() {}();1 > function() {}();

          48、一次性函數(shù)

          適合運(yùn)行一些只需要執(zhí)行一次的初始化代碼。

          function Func() {    console.log("x");    Func = function() {        console.log("y");    }}

          49、延遲加載函數(shù)

          當(dāng)函數(shù)中的復(fù)雜判斷分支越來(lái)越多時(shí),可以大大節(jié)省資源開銷。

          function Func() {    if (a === b) {        console.log("x");    } else {        console.log("y");    }}// replace withfunction Func() {    if (a === b) {        Func = function() {            console.log("x");        }    } else {        Func = function() {            console.log("y");        }    }    return Func();}

          50、檢測(cè)非空參數(shù)

          function IsRequired() {    throw new Error("param is required");}function Func(name = IsRequired()) {    console.log("I Love " + name);}Func(); // "param is required"Func("You"); // "I Love You"

          51、字符串創(chuàng)建函數(shù)

          const Func = new Function("name", "console.log(\"I Love \" + name)");

          52、優(yōu)雅地處理錯(cuò)誤信息

          try {    Func();} catch (e) {    location. + e.message;}

          53、優(yōu)雅地處理 Async/Await 參數(shù)

          function AsyncTo(promise) {    return promise.then(data => [null, data]).catch(err => [err]);}const [err, res] = await AsyncTo(Func());

          54、優(yōu)雅地處理多個(gè)函數(shù)返回值

          function Func() {    return Promise.all([        fetch("/user"),        fetch("/comment")    ]);}const [user, comment] = await Func();

          DOM 技能

          55、顯示所有 DOM 邊框

          [].forEach.call($$("*"), dom => {    dom.style.outline = "1px solid #" + (~~(Math.random() * (1 << 24))).toString(16);});

          56、響應(yīng)式頁(yè)面

          頁(yè)面基于設(shè)計(jì)圖但需要適配多個(gè)模型,元素大小使用rem設(shè)置。

          function AutoResponse(width = 750) {    const target = document.documentElement;    target.clientWidth >= 600        ? (target.style.fontSize = "80px")        : (target.style.fontSize = target.clientWidth / width * 100 + "px");}

          57、過(guò)濾 XSS

          function FilterXss(content) {    let elem = document.createElement("div");    elem.innerText = content;    const result = elem.innerHTML;    elem = null;    return result;}

          58、訪問(wèn)本地存儲(chǔ)

          const love = JSON.parse(localStorage.getItem("love"));localStorage.setItem("love", JSON.stringify("I Love You"));

          總結(jié)

          以上就是我整理匯總的58個(gè)JavaScript的小技巧,希望對(duì)你有所幫助。

          感謝您的閱讀,祝編程愉快!


          學(xué)習(xí)更多技能

          請(qǐng)點(diǎn)擊下方公眾號(hào)

          瀏覽 34
          點(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无码秘 蜜桃渚光希 | 无码人妻精品一二三在线99绯色 |