本文主要寫的是本身經常使用的一些javaScript 代碼塊。記錄經常使用代碼,方便查閱。如發現錯誤,歡迎留言改正。java
閱讀三連:點贊(👍)、關注(😍)、收藏(📝)。web
function formatParamsToObject() { let search = window.location.search, // 獲取url的參數部分 obj = {}; if (!search) return obj; let params = search.split('?')[1]; // 獲取參數 let paramsArr = params.split('&'); // 遍歷數組 for (let i of paramsArr) { let arr = i.split('='); obj[arr[0]] = arr[1] // 設置對象key,value } return obj }
舉個栗子 → 🙌🌰:www.baidu.com?id=1&type=2ajax
formatParamsToObject() // {id: "1", type: "2"}
function formatObjToParamStr(obj, tag = true) { let data = [], dStr = ''; for (let key in obj) { data.push(`${key}=${obj[key]}`); } dStr = tag ? '?' + data.join('&') : data.join('&'); return dStr }
舉個栗子 → 🙌🌰:json
formatObjToParamStr({id:1,type:2}) // "?id=1&type=2" formatObjToParamStr({id:1,type:2},false) // "id=1&type=2"
function getUrlParam(name,url) { let search = url || window.location.search, reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i'), r = search.substr(search.indexOf('\?') + 1).match(reg); return r != null ? r[2] : ''; }
舉個栗子 → 🙌🌰:www.baidu.com?id=1&type=2canvas
getUrlParam('id','www.baidu.com?id=1&type=2') // 1
function setCookie(name, value, expiretime) { let cookie = `${name}=${encodeURIComponent(value)}; path=/`; if (typeof expiretime === 'number')cookie += `; max-age=${(60*60*24*expiretime)}`; document.cookie = cookie; }
舉個栗子 → 🙌🌰:api
setCookie('id',1,1) document.cookie //"id=1"
function getCookie(name) { let cookie = document.cookie; let arrCookie = cookie.split('; '); for (let i = 0; i < arrCookie.length; i++) { let arr = arrCookie[i].split('='); if (arr[0] == name) return arr[1]; } }
舉個栗子 → 🙌🌰跨域
getCookie('id') // 1
max-age爲0時,刪除cookie數組
function deleteCookie(name) { let currentCookie = getCookie(name); if (currentCookie) document.cookie = name + '=' + currentCookie + `; max-age=0}; path=/`; }
舉個栗子 → 🙌🌰緩存
deleteCookie('id') document.cookie // ''
在必定的時間內,屢次執行同一個函數,只會觸發一次服務器
function debounce(fn,delay) { let timer = null; return function () { if(timer) clearTimeout(timer); timer = setTimeout(fn,delay) } }
在必定時間內,屢次執行同一個函數,只有第一次執行纔會觸發。
function throttle(fn,delay) { let flag = true; return function () { if(!flag) return false; flag = false; setTimeout(()=> { fn(); flag = false; },delay); } }
舉個栗子 → 🙌🌰
場景:以一個輸入框爲例,監聽鼠標彈起事件,在1s時間內, 輸出時間戳,屢次輸入,只會執行一次。
let ele = document.getElementsByTagName('input')[0]; ele.addEventListener('keyup',throttle(()=>{ console.log(Date.now()); },1000));
function checkPhone(phone) { return /^1[3|4|5|6|7|8|9]d{9}$/.test(phone); }
舉個栗子 → 🙌🌰
checkPhone(18900008888) // true 此號碼隨機寫的,如能夠撥打,告知修改
function checkTel (tel) { return /^((d{3,4})|d{3,4}-|s)?d{5,14}$/.test(tel) }
舉個栗子 → 🙌🌰
checkTel('12306') // true 12306服務熱線 checkTel('95105105') // true 12306 訂票熱線 checkTel('0755-12306') //true
function isArray (val) { return Object.prototype.toString.call(val) === '[object Array]'; }
舉個栗子 → 🙌🌰
isArray([]) // true isArray({}) // false
function isObject(val) { return Object.prototype.toString.call(val) === '[object Object]'; }
舉個栗子 → 🙌🌰
isObject([]) // false isObject({}) // true
function isNumber(val) { return Object.prototype.toString.call(val) === '[object Number]'; }
舉個栗子 → 🙌🌰
isNumber(12) // true isNumber({}) // false
function checkObjHasAtrr(obj, key) { return Object.prototype.hasOwnProperty.call(obj, key); }
舉個栗子 → 🙌🌰
checkObjHasAtrr({id: 1, type: 2}, 'id') // true
function max (arr) { if (!isArray(arr) && arr.length) return; return Math.max.apply(null,arr); }
舉個栗子 → 🙌🌰
max([1,2,3,4,5,6]) // 6
function min(arr) { if (!isArray(arr) && arr.length) return; return Math.min.apply(null, arr); }
舉個栗子 → 🙌🌰
min([1,2,3,4,5,6]) // 1
function toArray (list, start) { start = start || 0; let i = list.length - start; let ret = new Array(i); while (i--) { ret[i] = list[i + start]; } return ret; }
舉個栗子 → 🙌🌰
toArray([1,2,3,4,5,6], 2) // [3, 4, 5, 6]
說明:
Math.floor:下取整
Math.random:生成0~1 的隨機數
function getRandom(min,max) { return Math.floor(Math.random() * (max - min + 1)) + min; }
舉個栗子 → 🙌🌰
getRandom(1,2) // 1 隨機生成[1,2]
去除首尾空格
function trim1(str) { return str.replace(/(^\s*)|(\s*$)/g, ''); }
去除字符串全部空格
function trim2(str) { return str.replace(/(\s+)/g, ''); }
舉個栗子 → 🙌🌰
trim1(' web api ') // 'web api' trim2(' web api ') // 'webapi'
preventDefault用於取消一個目標元素的默認行爲。默認事件,好比a標籤,點擊默認跳轉。
function preventDefault(e) { e = e || window.event; if (e & e.preventDefault) e.preventDefault(); else e.returnValue = false; //IE低版本 }
舉個栗子 → 🙌🌰
鼠標點擊右鍵,阻止默認事件(oncontextmenu)彈起
document.oncontextmenu = function (e) { preventDefault(e); }
事件冒泡:如在一個按鈕是綁定一個」click」事件,那麼」click」事件會依次在它的父級元素中被觸發 。
function stopPropagation(e) { e = e || window.event; if (e & e.stopPropagation) e.stopPropagation(); else e.cancelBubble = true; }
舉個栗子 → 🙌🌰
已input,body爲慄:
let btn = document.querySelector('input'); let oBody = document.querySelector('body'); btn.onclick = function (e) { stopPropagation(e); // 1 // stopPropagation(e); // 1,2 console.log(1) } oBody.onclick = function () { console.log(2); }
function formatObjToArr(obj) { if (!isObject(obj)) return []; let options = []; for (let i in obj) options.push({ name: obj[i], key: i }); return options; }
舉個栗子 → 🙌🌰
formatObjToArr({1: 'Jack', 2: 'Tom'}) // [{name: "Jack", key: "1"},{name: "Tom", key: "2"}
function removeArr(arr, val) { let index = arr.indexOf(val); if (index > -1) arr.splice(index, 1); return arr; }
舉個栗子 → 🙌🌰
removeArr([1,2,3,4,5,6,7,8],4) // [1, 2, 3, 5, 6, 7, 8]
function uniqueArr(arr) { return Array.from(new Set(arr)); }
舉個栗子 → 🙌🌰
uniqueArr([1, 2, 1, 3]) //[1, 2, 3]
注: 在微信自帶的遊覽器中不支持,微信會攔截,能夠使用微信的JS-SDK。 服務器端須要設置容許跨域:access-control-allow-origin: *
function downImage(imageSrc, name) { let image = new Image(); // 處理canvas 跨域問題 image.setAttribute('crossOrigin', 'anonymous'); image.onload = function() { let canvas = document.createElement('canvas'); let context = canvas.getContext('2d'); canvas.width = image.width; canvas.height = image.height; context.drawImage(image, 0, 0, image.width, image.height); let url = canvas.toDataURL('image/png'); // 圖片編碼數據 let a = document.createElement('a'); let event = new MouseEvent('click'); // 建立一個單擊事件 a.download = name || 'image'; // 設置圖片名稱 a.href = url; // 將生成的URL設置爲a.href屬性 a.dispatchEvent(event); // 觸發a的單擊事件 a = null,canvas = null; } image.src = imageSrc; }
舉個栗子 → 🙌🌰
downImage('https://bkimg.cdn.bcebos.com/pic/94cad1c8a786c9179e80a80cc23d70cf3bc75700?x-bce-process=image/watermark,image_d2F0ZXIvYmFpa2U5Mg==,g_7,xp_5,yp_5')
function deepCopy(obj, cache) { if (cache === void 0) cache = []; if (obj === null || typeof obj !== 'object') { return obj } let copy = Array.isArray(obj) ? [] : {}; // 設置緩存,用於下面遞歸引用 cache.push({ original: obj, copy: copy }); Object.keys(obj).forEach(function(key) { copy[key] = deepCopy(obj[key], cache); }); return copy }
舉個栗子 → 🙌🌰
let obj = { id: 1, name: 'fishStudy520', data: [], getName: function() { return this.name } } deepCopy(obj);
function getCode(time) { let setInter = null, codeText = ''; setInter = setInterval(() => { if (time < 1) { clearInterval(setInter); codeText = '獲取驗證碼'; } else { codeText = `已發送${ time }s`; time--; } }, 1000); }
舉個栗子 → 🙌🌰
getCode(5)
function replaceMobile(mobile) { return Number.prototype.toString.call(mobile).replace(/1(\d{2})\d{4}(\d{4})/g,'1$1****$2'); }
舉個栗子 → 🙌🌰
replaceMobile(18000009999) //"180****9999"
function request(obj) { return new Promise(function(resolve, reject) { let { url, method = 'GET', params = {}, isAsync = true } = obj; method = method.toUpperCase(); let xhr = new XMLHttpRequest(); // 建立一個 XMLHttpRequest對象 if (method === "POST") { xhr.open(method, url, isAsync); xhr.setRequestHeader('Content-type', 'application/json'); // json 數據格式(已json數據格式爲例) xhr.send(JSON.stringify(params)); // json 字符串 } else { let paramsStr = formateObjToParamStr(params); xhr.open(method, url + paramsStr, isAsync); //參數已url 方式傳遞 xhr.send(); } xhr.onreadystatechange = function() { if (xhr.status === 200 && xhr.readyState === 4) { let response = JSON.parse(xhr.responseText); resolve(response) } else if (xhr.readyState === 4) { reject({ code: xhr.status, message: xhr.statusText }) } } }).catch((e) => console.log(e)) }
舉個栗子 → 🙌🌰
// 當前項目裏建立 data.json 文件 { "code": 200, "data": [{ "id": 1, "name": "JavaScript 高級程序設計第三版" }, { "id": 2, "name": "JavaScript 權威指南" }, { "id": 3, "name": "你不知道的JavaScript《上》" }, { "id": 4, "name": "你不知道的JavaScript《中》" }, { "id": 5, "name": "你不知道的JavaScript《下》" } ] } // 函數調用 (async function getRequestList() { let res = await request({ url: 'data.json', method: 'GET', }); console.log(res); })(); // 直接調用 request({ url: 'data.json', method: 'GET',}).then(res=> { console.log(res) })
val: 數字
size: 長度
function addZero(val, size) { for (let i = 0, len = size - (val + '').length; i < len; i++) { val = '0' + val; }; return val + ''; }
舉個栗子 → 🙌🌰
addZero(20,5) // "00020"
若是喜歡那就點個讚唄(👍👍👍)! (╯ε╰)(╯ε╰)(╯ε╰)