日本综合一区二区|亚洲中文天堂综合|日韩欧美自拍一区|男女精品天堂一区|欧美自拍第6页亚洲成人精品一区|亚洲黄色天堂一区二区成人|超碰91偷拍第一页|日韩av夜夜嗨中文字幕|久久蜜综合视频官网|精美人妻一区二区三区

RELATEED CONSULTING
相關咨詢
服務時間:8:30-17:00
你可能遇到了下面的問題
關閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
靈活運用JS開發(fā)技巧

 前言

創(chuàng)新互聯(lián)建站長期為千余家客戶提供的網(wǎng)站建設服務,團隊從業(yè)經(jīng)驗10年,關注不同地域、不同群體,并針對不同對象提供差異化的產(chǎn)品和服務;打造開放共贏平臺,與合作伙伴共同營造健康的互聯(lián)網(wǎng)生態(tài)環(huán)境。為南譙企業(yè)提供專業(yè)的網(wǎng)站設計制作、網(wǎng)站設計,南譙網(wǎng)站改版等技術(shù)服務。擁有十余年豐富建站經(jīng)驗和眾多成功案例,為您定制開發(fā)。

何為技巧,意指表現(xiàn)在文學、工藝、體育等方面的巧妙技能。代碼作為一門現(xiàn)代高級工藝,推動著人類科學技術(shù)的發(fā)展,同時猶如文字一樣承托著人類文化的進步。

每寫好一篇文章,都會使用大量的寫作技巧。烘托、渲染、懸念、鋪墊、照應、伏筆、聯(lián)想、想象、抑揚結(jié)合、點面結(jié)合、動靜結(jié)合、敘議結(jié)合、情景交融、首尾呼應、襯托對比、白描細描、比喻象征、借古諷今、卒章顯志、承上啟下、開門見山、動靜相襯、虛實相生、實寫虛寫、托物寓意、詠物抒情等,這些應該都是我們從小到大寫文章而接觸到的寫作技巧。

作為程序猿的我們,寫代碼同樣也需要大量的寫作技巧。一份良好的代碼能讓人耳目一新,讓人容易理解,讓人舒服自然,同時也讓自己成就感滿滿(哈哈,這個才是重點)。因此,我整理下三年來自己使用到的一些JS開發(fā)技巧,希望能讓你寫出耳目一新、容易理解、舒服自然的代碼。

以下演示全是ES6版本的書寫,在Webpack和Babel的加持下就不能好好寫ES6嗎,還寫什么ES3和ES5呢,更別管那弱智的IE瀏覽器了,IE瀏覽器都快被淘汰了,Microsoft都宣布放棄使用自研的瀏覽器內(nèi)核而使用Google開源的Chromium內(nèi)核了。

目錄

既然寫文章有這么多的寫作技巧,那么我也需要對JS開發(fā)技巧整理一下,起個易記的名字。

  •  String Skill:字符串技巧
  •  Number Skill:數(shù)值技巧
  •  Boolean Skill:布爾值技巧
  •  Array Skill:數(shù)組技巧
  •  Object Skill:對象技巧
  •  Function Skill:函數(shù)技巧
  •  DOM Skill:DOM技巧

備注

  •  代碼只作演示用途,不會詳細說明ES6語法
  •  如有不明白的語法問題請參考阮一峰老師的《ES6標準入門》
  • 《ES6標準入門》一直保持更新,建議收藏,平時查看

String Skill

對比時間

時間個位數(shù)形式需補0 

 
 
 
  1. const time1 = "2019-02-14 21:00:00";  
  2. const time2 = "2019-05-01 09:00:00";  
  3. const overtime = time1 > time2;  
  4. // overtime => false 

格式化金錢 

 
 
 
  1. const ThousandNum = num => num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");  
  2. const money = ThousandNum(20190214);  
  3. // money => "20,190,214" 

生成隨機ID 

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

生成隨機HEX色值 

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

生成星級評分 

 
 
 
  1. const StartScore = rate => "".slice(5 - rate, 10 - rate);  
  2. const start = StartScore(3);  
  3. // start => "" 

操作URL查詢參數(shù) 

 
 
 
  1. const params = new URLSearchParams(location.search.replace(/\?/ig, "")); // location.search = "?name=young&sex=male"  
  2. params.has("young"); // true  
  3. params.get("sex"); // "male" 

Number Skill

取整

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

 
 
 
  1. const num1 = ~~ 1.69;  
  2. const num2 = 1.69 | 0;  
  3. const num3 = 1.69 >> 0;  
  4. // num1 num2 num3 => 1 1 1 

補零 

 
 
 
  1. const FillZero = (num, len) => num.toString().padStart(len, "0");  
  2. const num = FillZero(169, 5);  
  3. // num => "00169" 

轉(zhuǎn)數(shù)值

只對null、""、false、數(shù)值字符串有效 

 
 
 
  1. const num1 = +null;  
  2. const num2 = +"";  
  3. const num3 = +false;  
  4. const num4 = +"169";  
  5. // num1 num2 num3 num4 => 0 0 0 169 

時間戳 

 
 
 
  1. const timestamp = +new Date("2019-02-14");  
  2. // timestamp => 1550102400000 

精確小數(shù) 

 
 
 
  1. const RoundNum = (num, decimal) => Math.round(num * 10 ** decimal) / 10 ** decimal;  
  2. const num = RoundNum(1.69, 1);  
  3. // num => 1.7 

判斷奇偶 

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

取最小最大值 

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

生成范圍隨機數(shù) 

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

Boolean Skill

短路運算符 

 
 
 
  1. const a = d && 1; // 滿足條件賦值:取假運算,從左到右依次判斷,遇到假值返回假值,后面不再執(zhí)行,否則返回最后一個真值  
  2. const b = d || 1; // 默認賦值:取真運算,從左到右依次判斷,遇到真值返回真值,后面不再執(zhí)行,否則返回最后一個假值  
  3. const c = !d; // 取假賦值:單個表達式轉(zhuǎn)換為true則返回false,否則返回true 

判斷數(shù)據(jù)類型

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

 
 
 
  1. function DataType(tgt, type) {  
  2.     const dataType = Object.prototype.toString.call(tgt).replace(/\[object /g, "").replace(/\]/g, "").toLowerCase();  
  3.     return type ? dataType === type : dataType;  
  4. }  
  5. DataType("young"); // "string"  
  6. DataType(20190214); // "number"  
  7. DataType(true); // "boolean"  
  8. DataType([], "array"); // true  
  9. DataType({}, "array"); // false 

是否為空數(shù)組 

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

是否為空對象 

 
 
 
  1. const obj = {};  
  2. const flag = DataType(obj, "object") && !Object.keys(obj).length;  
  3. // flag => true 

滿足條件時執(zhí)行 

 
 
 
  1. const flagA = true; // 條件A  
  2. const flagB = false; // 條件B  
  3. (flagA || flagB) && Func(); // 滿足A或B時執(zhí)行  
  4. (flagA || !flagB) && Func(); // 滿足A或不滿足B時執(zhí)行  
  5. flagA && flagB && Func(); // 同時滿足A和B時執(zhí)行  
  6. flagA && !flagB && Func(); // 滿足A且不滿足B時執(zhí)行 

為非假值時執(zhí)行 

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

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

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

對象不為空時執(zhí)行 

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

函數(shù)退出代替條件分支退出 

 
 
 
  1. if (flag) {  
  2.     Func();  
  3.     return false;  
  4. }  
  5. // 換成  
  6. if (flag) {  
  7.     return Func();  

switch/case使用區(qū)間 

 
 
 
  1. const age = 26;  
  2. switch (true) {  
  3.     case isNaN(age):  
  4.         console.log("not a number");  
  5.         break;  
  6.     case (age < 18):  
  7.         console.log("under age");  
  8.         break;  
  9.     case (age >= 18):  
  10.         console.log("adult");  
  11.         break;  
  12.     default:  
  13.         console.log("please set your age");  
  14.         break;  

Array Skill

克隆數(shù)組 

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

合并數(shù)組 

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

去重數(shù)組 

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

混淆數(shù)組 

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

清空數(shù)組 

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

截斷數(shù)組 

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

交換賦值 

 
 
 
  1. let a = 0;  
  2. let b = 1;  
  3. [a, b] = [b, a];  
  4. // a b => 1 0 

過濾空值

空值:undefined、null、""、0、false、NaN 

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

異步累計 

 
 
 
  1. async function Func(deps) {  
  2.     return deps.reduce(async(t, v) => {  
  3.         const dep = await t;  
  4.         const version = await Todo(v);  
  5.         dep[v] = version;  
  6.         return dep;  
  7.     }, Promise.resolve({}));  
  8. }  
  9. const result = await Func(); // 需在async包圍下使用 

數(shù)組首部插入成員 

 
 
 
  1. let arr = [1, 2]; // 以下方法任選一種  
  2. arr.unshift(0);  
  3. arr = [0].concat(arr);  
  4. arr = [0, ...arr];  
  5. // arr => [0, 1, 2] 

數(shù)組尾部插入成員 

 
 
 
  1. let arr = [0, 1]; // 以下方法任選一種  
  2. arr.push(2);  
  3. arr.concat(2);  
  4. arr[arr.length] = 2;  
  5. arr = [...arr, 2];  
  6. // arr => [0, 1, 2] 

統(tǒng)計數(shù)組成員個數(shù) 

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

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

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

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

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

解構(gòu)數(shù)組成員默認值 

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

獲取隨機數(shù)組成員 

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

創(chuàng)建指定長度數(shù)組 

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

創(chuàng)建指定長度且值相等的數(shù)組 

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

reduce代替map和filter 

 
 
 
  1. const _arr = [0, 1, 2];   
  2. // map  
  3. const arr = _arr.map(v => v * 2);  
  4. const arr = _arr.reduce((t, c) => {  
  5.     t.push(c * 2);  
  6.     return t;  
  7. }, []);  
  8. // arr => [0, 2, 4]  
  9. // filter  
  10. const arr = _arr.filter(v => v > 0);  
  11. const arr = _arr.reduce((t, c) => {  
  12.     c > 0 && t.push(c);  
  13.     return t;  
  14. }, []);  
  15. // arr => [1, 2]  
  16. // map和filter  
  17. const arr = _arr.map(v => v * 2).filter(v => v > 2);  
  18. const arr = _arr.reduce((t, c) => {  
  19.     cc = c * 2;  
  20.     c > 2 && t.push(c);  
  21.     return t;  
  22. }, []);  
  23. // arr => [4] 

Object Skill

克隆對象 

 
 
 
  1. const _obj = { a: 0, b: 1, c: 2 }; // 以下方法任選一種  
  2. const obj = { ..._obj };  
  3. const obj = JSON.parse(JSON.stringify(_obj));  
  4. // obj => { a: 0, b: 1, c: 2 } 

合并對象 

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

對象字面量

獲取環(huán)境變量時必用此方法,用它一直爽,一直用它一直爽 

 
 
 
  1. const env = "prod";  
  2. const link = {  
  3.     dev: "Development Address",  
  4.     test: "Testing Address",  
  5.     prod: "Production Address"  
  6. }[env];  
  7. // link => "Production Address" 

對象變量屬性 

 
 
 
  1. const flag = false;  
  2. const obj = {  
  3.     a: 0,  
  4.     b: 1,  
  5.     [flag ? "c" : "d"]: 2  
  6. };  
  7. // obj => { a: 0, b: 1, d: 2 } 

創(chuàng)建純空對象 

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

刪除對象無用屬性 

 
 
 
  1. const obj = { a: 0, b: 1, c: 2 }; // 只想拿b和c  
  2. const { a, ...rest } = obj;  
  3. // rest => { b: 1, c: 2 } 

解構(gòu)對象屬性嵌套 

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

解構(gòu)對象屬性別名 

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

解構(gòu)對象屬性默認值 

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

Function Skill

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

 
 
 
  1. const Func = function() {}(); // 常用  
  2. (function() {})(); // 常用  
  3. (function() {}()); // 常用  
  4. [function() {}()];  
  5. + function() {}();  
  6. - function() {}();  
  7. ~ function() {}();  
  8. ! function() {}();  
  9. new function() {};  
  10. new function() {}();  
  11. void function() {}();  
  12. typeof function() {}();  
  13. delete function() {}();  
  14. 1, function() {}();  
  15. 1 ^ function() {}();  
  16. 1 > function() {}(); 

隱式返回值

只能用于單語句返回值箭頭函數(shù),如果返回值是對象必須使用()包住 

 
 
 
  1. const Func = function(name) {  
  2.     return "I Love " + name;  
  3. };  
  4. // 換成  
  5. const Func = name => "I Love " + name; 

一次性函數(shù)

適用于運行一些只需執(zhí)行一次的初始化代碼 

 
 
 
  1. function Func() {  
  2.     console.log("x");  
  3.     Func = function() {  
  4.         console.log("y");  
  5.     }  

惰性載入函數(shù)

函數(shù)內(nèi)判斷分支較多較復雜時可大大節(jié)約資源開銷 

 
 
 
  1. function Func() {  
  2.     if (a === b) {  
  3.         console.log("x");  
  4.     } else {  
  5.         console.log("y");  
  6.     }  
  7. }  
  8. // 換成  
  9. function Func() {  
  10.     if (a === b) {  
  11.         Func = function() {  
  12.             console.log("x");  
  13.         }  
  14.     } else {  
  15.         Func = function() {  
  16.             console.log("y");  
  17.         }  
  18.     }  
  19.     return Func();  

檢測非空參數(shù) 

 
 
 
  1. function IsRequired() {  
  2.     throw new Error("param is required");  
  3. }  
  4. function Func(name = IsRequired()) {  
  5.     console.log("I Love " + name);  
  6. }  
  7. Func(); // "param is required"  
  8. Func("You"); // "I Love You" 

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

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

優(yōu)雅處理錯誤信息 

 
 
 
  1. try {  
  2.     Func();  
  3. } catch (e) {  
  4.     location.href = "https://stackoverflow.com/search?q=[js]+" + e.message;  

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

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

優(yōu)雅處理多個函數(shù)返回值 

 
 
 
  1. function Func() {  
  2.     return Promise.all([  
  3.         fetch("/user"),  
  4.         fetch("/comment")  
  5.     ]);  
  6. }  
  7. const [user, comment] = await Func(); // 需在async包圍下使用 

DOM Skill

顯示全部DOM邊框

調(diào)試頁面元素邊界時使用 

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

自適應頁面

頁面基于一張設計圖但需做多款機型自適應,元素尺寸使用rem進行設置 

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

過濾XSS 

 
 
 
  1. function FilterXss(content) {  
  2.     let elem = document.createElement("div");  
  3.     elem.innerText = content;  
  4.     const result = elem.innerHTML;  
  5.     elem = null;  
  6.     return result;  

存取LocalStorage

反序列化取,序列化存 

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

結(jié)語

寫到最后總結(jié)得差不多了,后續(xù)如果我想起還有哪些JS開發(fā)技巧遺漏的,會繼續(xù)在這篇文章上補全,同時也希望各位朋友對文章里的要點進行補充或者提出自己的見解。歡迎在下方進行評論或補充喔,喜歡的點個贊或收個藏,保證你在開發(fā)時用得上。

最后送大家一個鍵盤! 

 
 
 
  1. (_=>[..."`1234567890-=~~QWERTYUIOP[]\\~ASDFGHJKL;'~~ZXCVBNM,./~"].map(x=>(o+=`/${b='_'.repeat(w=x
  2.  `)()  

網(wǎng)站欄目:靈活運用JS開發(fā)技巧
文章鏈接:http://www.dlmjj.cn/article/djopooh.html