靈活運(yùn)用JS開發(fā)技巧
前言
何為技巧,意指表現(xiàn)在文學(xué)、工藝、體育等方面的巧妙技能。代碼作為一門現(xiàn)代高級(jí)工藝,推動(dòng)著人類科學(xué)技術(shù)的發(fā)展,同時(shí)猶如文字一樣承托著人類文化的進(jìn)步。
每寫好一篇文章,都會(huì)使用大量的寫作技巧。烘托、渲染、懸念、鋪墊、照應(yīng)、伏筆、聯(lián)想、想象、抑揚(yáng)結(jié)合、點(diǎn)面結(jié)合、動(dòng)靜結(jié)合、敘議結(jié)合、情景交融、首尾呼應(yīng)、襯托對(duì)比、白描細(xì)描、比喻象征、借古諷今、卒章顯志、承上啟下、開門見山、動(dòng)靜相襯、虛實(shí)相生、實(shí)寫虛寫、托物寓意、詠物抒情等,這些應(yīng)該都是我們從小到大寫文章而接觸到的寫作技巧。
作為程序猿的我們,寫代碼同樣也需要大量的寫作技巧。一份良好的代碼能讓人耳目一新,讓人容易理解,讓人舒服自然,同時(shí)也讓自己成就感滿滿(哈哈,這個(gè)才是重點(diǎn))。因此,我整理下三年來自己使用到的一些JS開發(fā)技巧,希望能讓你寫出耳目一新、容易理解、舒服自然的代碼。
以下演示全是ES6版本的書寫,在Webpack和Babel的加持下就不能好好寫ES6嗎,還寫什么ES3和ES5呢,更別管那弱智的IE瀏覽器了,IE瀏覽器都快被淘汰了,Microsoft都宣布放棄使用自研的瀏覽器內(nèi)核而使用Google開源的Chromium內(nèi)核了。
目錄
既然寫文章有這么多的寫作技巧,那么我也需要對(duì)JS開發(fā)技巧整理一下,起個(gè)易記的名字。
- String Skill:字符串技巧
- Number Skill:數(shù)值技巧
- Boolean Skill:布爾值技巧
- Array Skill:數(shù)組技巧
- Object Skill:對(duì)象技巧
- Function Skill:函數(shù)技巧
- DOM Skill:DOM技巧
備注
- 代碼只作演示用途,不會(huì)詳細(xì)說明ES6語法
- 如有不明白的語法問題請(qǐng)參考阮一峰老師的《ES6標(biāo)準(zhǔn)入門》
- 《ES6標(biāo)準(zhǔn)入門》一直保持更新,建議收藏,平時(shí)查看
String Skill
對(duì)比時(shí)間
時(shí)間個(gè)位數(shù)形式需補(bǔ)0
- const time1 = "2019-02-14 21:00:00";
- const time2 = "2019-05-01 09:00:00";
- const overtime = time1 > time2;
- // overtime => false
格式化金錢
- const ThousandNum = num => num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
- const money = ThousandNum(20190214);
- // money => "20,190,214"
生成隨機(jī)ID
- const RandomId = len => Math.random().toString(36).substr(3, len);
- const id = RandomId(10);
- // id => "jg7zpgiqva"
生成隨機(jī)HEX色值
- const RandomColor = () => "#" + Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0");
- const color = RandomColor();
- // color => "#f03665"
生成星級(jí)評(píng)分
- const StartScore = rate => "★★★★★☆☆☆☆☆".slice(5 - rate, 10 - rate);
- const start = StartScore(3);
- // start => "★★★"
操作URL查詢參數(shù)
- const params = new URLSearchParams(location.search.replace(/\?/ig, "")); // location.search = "?name=young&sex=male"
- params.has("young"); // true
- params.get("sex"); // "male"
Number Skill
取整
代替正數(shù)的Math.floor(),代替負(fù)數(shù)的Math.ceil()
- const num1 = ~~ 1.69;
- const num2 = 1.69 | 0;
- const num3 = 1.69 >> 0;
- // num1 num2 num3 => 1 1 1
補(bǔ)零
- const FillZero = (num, len) => num.toString().padStart(len, "0");
- const num = FillZero(169, 5);
- // num => "00169"
轉(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
時(shí)間戳
- const timestamp = +new Date("2019-02-14");
- // timestamp => 1550102400000
精確小數(shù)
- const RoundNum = (num, decimal) => Math.round(num * 10 ** decimal) / 10 ** decimal;
- const num = RoundNum(1.69, 1);
- // num => 1.7
判斷奇偶
- const OddEven = num => !!(num & 1) ? "odd" : "even";
- const num = OddEven(2);
- // num => "even"
取最小最大值
- const arr = [0, 1, 2];
- const min = Math.min(...arr);
- const max = Math.max(...arr);
- // min max => 0 2
生成范圍隨機(jī)數(shù)
- const RandomNum = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
- const num = RandomNum(1, 10);
Boolean Skill
短路運(yùn)算符
- const a = d && 1; // 滿足條件賦值:取假運(yùn)算,從左到右依次判斷,遇到假值返回假值,后面不再執(zhí)行,否則返回最后一個(gè)真值
- const b = d || 1; // 默認(rèn)賦值:取真運(yùn)算,從左到右依次判斷,遇到真值返回真值,后面不再執(zhí)行,否則返回最后一個(gè)假值
- const c = !d; // 取假賦值:單個(gè)表達(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
- function DataType(tgt, type) {
- const dataType = Object.prototype.toString.call(tgt).replace(/\[object /g, "").replace(/\]/g, "").toLowerCase();
- return type ? dataType === type : dataType;
- }
- DataType("young"); // "string"
- DataType(20190214); // "number"
- DataType(true); // "boolean"
- DataType([], "array"); // true
- DataType({}, "array"); // false
是否為空數(shù)組
- const arr = [];
- const flag = Array.isArray(arr) && !arr.length;
- // flag => true
是否為空對(duì)象
- const obj = {};
- const flag = DataType(obj, "object") && !Object.keys(obj).length;
- // flag => true
滿足條件時(shí)執(zhí)行
- const flagA = true; // 條件A
- const flagB = false; // 條件B
- (flagA || flagB) && Func(); // 滿足A或B時(shí)執(zhí)行
- (flagA || !flagB) && Func(); // 滿足A或不滿足B時(shí)執(zhí)行
- flagA && flagB && Func(); // 同時(shí)滿足A和B時(shí)執(zhí)行
- flagA && !flagB && Func(); // 滿足A且不滿足B時(shí)執(zhí)行
為非假值時(shí)執(zhí)行
- const flag = false; // undefined、null、""、0、false、NaN
- !flag && Func();
數(shù)組不為空時(shí)執(zhí)行
- const arr = [0, 1, 2];
- arr.length && Func();
對(duì)象不為空時(shí)執(zhí)行
- const obj = { a: 0, b: 1, c: 2 };
- Object.keys(obj).length && Func();
函數(shù)退出代替條件分支退出
- if (flag) {
- Func();
- return false;
- }
- // 換成
- if (flag) {
- return Func();
- }
switch/case使用區(qū)間
- const age = 26;
- switch (true) {
- case isNaN(age):
- console.log("not a number");
- break;
- case (age < 18):
- console.log("under age");
- break;
- case (age >= 18):
- console.log("adult");
- break;
- default:
- console.log("please set your age");
- break;
- }
Array Skill
克隆數(shù)組
- const _arr = [0, 1, 2];
- const arr = [..._arr];
- // arr => [0, 1, 2]
合并數(shù)組
- const arr1 = [0, 1, 2];
- const arr2 = [3, 4, 5];
- const arr = [...arr1, ...arr2];
- // arr => [0, 1, 2, 3, 4, 5];
去重?cái)?shù)組
- const arr = [...new Set([0, 1, 1, null, null])];
- // arr => [0, 1, null]
混淆數(shù)組
- const arr = [0, 1, 2, 3, 4, 5].slice().sort(() => Math.random() - .5);
- // arr => [3, 4, 0, 5, 1, 2]
清空數(shù)組
- const arr = [0, 1, 2];
- arr.length = 0;
- // arr => []
截?cái)鄶?shù)組
- const arr = [0, 1, 2];
- arr.length = 2;
- // arr => [0, 1]
交換賦值
- let a = 0;
- let b = 1;
- [a, b] = [b, a];
- // a b => 1 0
過濾空值
空值:undefined、null、""、0、false、NaN
- const arr = [undefined, null, "", 0, false, NaN, 1, 2].filter(Boolean);
- // arr => [1, 2]
異步累計(jì)
- async function Func(deps) {
- return deps.reduce(async(t, v) => {
- const dep = await t;
- const version = await Todo(v);
- dep[v] = version;
- return dep;
- }, Promise.resolve({}));
- }
- const result = await Func(); // 需在async包圍下使用
數(shù)組首部插入成員
- let arr = [1, 2]; // 以下方法任選一種
- arr.unshift(0);
- arr = [0].concat(arr);
- arr = [0, ...arr];
- // arr => [0, 1, 2]
數(shù)組尾部插入成員
- let arr = [0, 1]; // 以下方法任選一種
- arr.push(2);
- arr.concat(2);
- arr[arr.length] = 2;
- arr = [...arr, 2];
- // arr => [0, 1, 2]
統(tǒng)計(jì)數(shù)組成員個(gè)數(shù)
- const arr = [0, 1, 1, 2, 2, 2];
- const count = arr.reduce((t, c) => {
- t[c] = t[c] ? ++ t[c] : 1;
- return t;
- }, {});
- // count => { 0: 1, 1: 2, 2: 3 }
解構(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
解構(gòu)數(shù)組成員別名
- const arr = [0, 1, 2];
- const { 0: a, 1: b, 2: c } = arr;
- // a b c => 0 1 2
解構(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
獲取隨機(jī)數(shù)組成員
- const arr = [0, 1, 2, 3, 4, 5];
- const randomItem = arr[Math.floor(Math.random() * arr.length)];
- // randomItem => 1
創(chuàng)建指定長度數(shù)組
- const arr = [...new Array(3).keys()];
- // arr => [0, 1, 2]
創(chuàng)建指定長度且值相等的數(shù)組
- const arr = new Array(3).fill(0);
- // arr => [0, 0, 0]
reduce代替map和filter
- const _arr = [0, 1, 2];
- // map
- const arr = _arr.map(v => v * 2);
- const arr = _arr.reduce((t, c) => {
- t.push(c * 2);
- return t;
- }, []);
- // arr => [0, 2, 4]
- // filter
- const arr = _arr.filter(v => v > 0);
- const arr = _arr.reduce((t, c) => {
- c > 0 && t.push(c);
- return t;
- }, []);
- // arr => [1, 2]
- // map和filter
- const arr = _arr.map(v => v * 2).filter(v => v > 2);
- const arr = _arr.reduce((t, c) => {
- cc = c * 2;
- c > 2 && t.push(c);
- return t;
- }, []);
- // arr => [4]
Object Skill
克隆對(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 }
合并對(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 }
對(duì)象字面量
獲取環(huán)境變量時(shí)必用此方法,用它一直爽,一直用它一直爽
- const env = "prod";
- const link = {
- dev: "Development Address",
- test: "Testing Address",
- prod: "Production Address"
- }[env];
- // link => "Production Address"
對(duì)象變量屬性
- const flag = false;
- const obj = {
- a: 0,
- b: 1,
- [flag ? "c" : "d"]: 2
- };
- // obj => { a: 0, b: 1, d: 2 }
創(chuàng)建純空對(duì)象
- const obj = Object.create(null);
- Object.prototype.a = 0;
- // obj => {}
刪除對(duì)象無用屬性
- const obj = { a: 0, b: 1, c: 2 }; // 只想拿b和c
- const { a, ...rest } = obj;
- // rest => { b: 1, c: 2 }
解構(gòu)對(duì)象屬性嵌套
- const obj = { a: 0, b: 1, c: { d: 2, e: 3 } };
- const { c: { d, e } } = obj;
- // d e => 2 3
解構(gòu)對(duì)象屬性別名
- const obj = { a: 0, b: 1, c: 2 };
- const { a, b: d, c: e } = obj;
- // a d e => 0 1 2
解構(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
Function Skill
函數(shù)自執(zhí)行
- const Func = function() {}(); // 常用
- (function() {})(); // 常用
- (function() {}()); // 常用
- [function() {}()];
- + function() {}();
- - function() {}();
- ~ function() {}();
- ! function() {}();
- new function() {};
- new function() {}();
- void function() {}();
- typeof function() {}();
- delete function() {}();
- 1, function() {}();
- 1 ^ function() {}();
- 1 > function() {}();
隱式返回值
只能用于單語句返回值箭頭函數(shù),如果返回值是對(duì)象必須使用()包住
- const Func = function(name) {
- return "I Love " + name;
- };
- // 換成
- const Func = name => "I Love " + name;
一次性函數(shù)
適用于運(yùn)行一些只需執(zhí)行一次的初始化代碼
- function Func() {
- console.log("x");
- Func = function() {
- console.log("y");
- }
- }
惰性載入函數(shù)
函數(shù)內(nèi)判斷分支較多較復(fù)雜時(shí)可大大節(jié)約資源開銷
- function Func() {
- if (a === b) {
- console.log("x");
- } else {
- console.log("y");
- }
- }
- // 換成
- function Func() {
- if (a === b) {
- Func = function() {
- console.log("x");
- }
- } else {
- Func = function() {
- console.log("y");
- }
- }
- return Func();
- }
檢測(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"
字符串創(chuàng)建函數(shù)
- const Func = new Function("name", "console.log(\"I Love \" + name)");
優(yōu)雅處理錯(cuò)誤信息
- try {
- Func();
- } catch (e) {
- location.href = "https://stackoverflow.com/search?q=[js]+" + e.message;
- }
優(yōu)雅處理Async/Await參數(shù)
- function AsyncTo(promise) {
- return promise.then(data => [null, data]).catch(err => [err]);
- }
- const [err, res] = await AsyncTo(Func());
優(yōu)雅處理多個(gè)函數(shù)返回值
- function Func() {
- return Promise.all([
- fetch("/user"),
- fetch("/comment")
- ]);
- }
- const [user, comment] = await Func(); // 需在async包圍下使用
DOM Skill
顯示全部DOM邊框
調(diào)試頁面元素邊界時(shí)使用
- [].forEach.call($$("*"), dom => {
- dom.style.outline = "1px solid #" + (~~(Math.random() * (1 << 24))).toString(16);
- });
自適應(yīng)頁面
頁面基于一張?jiān)O(shè)計(jì)圖但需做多款機(jī)型自適應(yīng),元素尺寸使用rem進(jìn)行設(shè)置
- function AutoResponse(width = 750) {
- const target = document.documentElement;
- target.clientWidth >= 600
- ? (target.style.fontSize = "80px")
- : (targettarget.style.fontSize = target.clientWidth / width * 100 + "px");
- }
過濾XSS
- function FilterXss(content) {
- let elem = document.createElement("div");
- elem.innerText = content;
- const result = elem.innerHTML;
- elem = null;
- return result;
- }
存取LocalStorage
反序列化取,序列化存
- const love = JSON.parse(localStorage.getItem("love"));
- localStorage.setItem("love", JSON.stringify("I Love You"));
結(jié)語
寫到最后總結(jié)得差不多了,后續(xù)如果我想起還有哪些JS開發(fā)技巧遺漏的,會(huì)繼續(xù)在這篇文章上補(bǔ)全,同時(shí)也希望各位朋友對(duì)文章里的要點(diǎn)進(jìn)行補(bǔ)充或者提出自己的見解。歡迎在下方進(jìn)行評(píng)論或補(bǔ)充喔,喜歡的點(diǎn)個(gè)贊或收個(gè)藏,保證你在開發(fā)時(shí)用得上。
最后送大家一個(gè)鍵盤!
- (_=>[..."`1234567890-=~~QWERTYUIOP[]\\~ASDFGHJKL;'~~ZXCVBNM,./~"].map(x=>(o+=`/${b='_'.repeat(w=x<y?2:' 667699'[x=["Bs","Tab","Caps","Enter"][p++]||'Shift',p])}\\|`,m+=y+(x+' ').slice(0,w)+y+y,n+=y+b+y+y,l+=' __'+b)[73]&&(k.push(l,m,n,o),l='',m=n=o=y),m=n=o=y='|',p=l=k=[])&&k.join`
- `)()