前言
活不多说,自己平时搜集的干货函数奉上。
干货函数
找出数字在数组中下一个相邻的元素
1let i = ""; 2let rr = []; 3 4const name = (n, arr1)=>{ 5 let num = Number(n); 6 for (let i = 0; i < arr1.length; i++) { 7 const element = arr1[i]; 8 if (element != num) { 9 rr.push(num--); 10 } 11 } 12 return rr.find((el) => { 13 let newel = String(el); 14 return arr1.includes(newel); 15 })} 16 17let arr = ["2", "4", "6", "8", "10", "12", "14", "16", "18", "20", "22", "24", "27", "30", "33", "36", "42", "48", "54", "60"] 18console.log(name('5',arr)); //4 19
格式化时间
1/** 2 * @param {number} time 3 * @param {string} option 4 * @returns {string} 5 */ 6function formatTime(time, option) { 7 if (('' + time).length === 10) { 8 time = parseInt(time) * 1000 9 } else { 10 time = +time 11 } 12 const d = new Date(time) 13 const now = Date.now() 14 15 const diff = (now - d) / 1000 16 17 if (diff < 30) { 18 return '刚刚' 19 } else if (diff < 3600) { 20 // less 1 hour 21 return Math.ceil(diff / 60) + '分钟前' 22 } else if (diff < 3600 * 24) { 23 return Math.ceil(diff / 3600) + '小时前' 24 } else if (diff < 3600 * 24 * 2) { 25 return '1天前' 26 } 27 if (option) { 28 return parseTime(time, option) 29 } else { 30 return ( 31 d.getMonth() + 32 1 + 33 '月' + 34 d.getDate() + 35 '日' + 36 d.getHours() + 37 '时' + 38 d.getMinutes() + 39 '分' 40 ) 41 } 42} 43
解析时间
1/** 2 * Parse the time to string 3 * @param {(Object|string|number)} time 4 * @param {string} cFormat 5 * @returns {string | null} 6 */ 7function parseTime(time, cFormat) { 8 if (arguments.length === 0 || !time) { 9 return null 10 } 11 const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}' 12 let date 13 if (typeof time === 'object') { 14 date = time 15 } else { 16 if ((typeof time === 'string')) { 17 if ((/^[0-9]+$/.test(time))) { 18 // support "1548221490638" 19 time = parseInt(time) 20 } else { 21 // support safari 22 // https://stackoverflow.com/questions/4310953/invalid-date-in-safari 23 time = time.replace(new RegExp(/-/gm), '/') 24 } 25 } 26 27 if ((typeof time === 'number') && (time.toString().length === 10)) { 28 time = time * 1000 29 } 30 date = new Date(time) 31 } 32 const formatObj = { 33 y: date.getFullYear(), 34 m: date.getMonth() + 1, 35 d: date.getDate(), 36 h: date.getHours(), 37 i: date.getMinutes(), 38 s: date.getSeconds(), 39 a: date.getDay() 40 } 41 const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => { 42 const value = formatObj[key] 43 // Note: getDay() returns 0 on Sunday 44 if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] } 45 return value.toString().padStart(2, '0') 46 }) 47 return time_str 48} 49
解析Url地址
1/** 2 * @param {string} url 3 * @returns {Object} 4 */ 5function param2Obj(url) { 6 const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ') 7 if (!search) { 8 return {} 9 } 10 const obj = {} 11 const searchArr = search.split('&') 12 searchArr.forEach(v => { 13 const index = v.indexOf('=') 14 if (index !== -1) { 15 const name = v.substring(0, index) 16 const val = v.substring(index + 1, v.length) 17 obj[name] = val 18 } 19 }) 20 return obj 21} 22
合并两个对象
1/** 2 * Merges two objects, giving the last one precedence 3 * @param {Object} target 4 * @param {(Object|Array)} source 5 * @returns {Object} 6 */ 7function objectMerge(target, source) { 8 if (typeof target !== 'object') { 9 target = {} 10 } 11 if (Array.isArray(source)) { 12 return source.slice() 13 } 14 Object.keys(source).forEach(property => { 15 const sourceProperty = source[property] 16 if (typeof sourceProperty === 'object') { 17 target[property] = objectMerge(target[property], sourceProperty) 18 } else { 19 target[property] = sourceProperty 20 } 21 }) 22 return target 23} 24
数组去重
1/** 2 * @param {Array} arr 3 * @returns {Array} 4 */ 5function uniqueArr(arr) { 6 return Array.from(new Set(arr)) 7} 8
防抖
1/** 2 * @param {Function} func 3 * @param {number} wait 4 * @param {boolean} immediate 5 * @return {*} 6 */ 7function debounce(func, wait, immediate) { 8 let timeout, args, context, timestamp, result 9 10 const later = function() { 11 // 据上一次触发时间间隔 12 const last = +new Date() - timestamp 13 14 // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait 15 if (last < wait && last > 0) { 16 timeout = setTimeout(later, wait - last) 17 } else { 18 timeout = null 19 // 如果设定为immediate===true,因为开始边界已经调用过了此处无需调用 20 if (!immediate) { 21 result = func.apply(context, args) 22 if (!timeout) context = args = null 23 } 24 } 25 } 26 27 return function(...args) { 28 context = this 29 timestamp = +new Date() 30 const callNow = immediate && !timeout 31 // 如果延时不存在,重新设定延时 32 if (!timeout) timeout = setTimeout(later, wait) 33 if (callNow) { 34 result = func.apply(context, args) 35 context = args = null 36 } 37 38 return result 39 } 40} 41
简易搜索
1<!DOCTYPE html> 2<html lang="en"> 3<head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 6 <title>Document</title> 7</head> 8<body> 9 <input type="text" id="int"> 10</body> 11<script> let list = ["示例1","示例12","示例5","示例56"]; 12 document.querySelector('#int').onchange=function(e){ 13 console.log(search(e.target.value)); 14 } 15 16 function search(val) { 17 if (val) { 18 return list.filter(function (item) { 19 return Object.keys(item).some(function (key) { 20 return String(item[key]).toLowerCase().indexOf(val) > -1 21 }) 22 }) 23 } 24 return list 25 }</script> 26</html> 27 28
将秒化为时分秒
1function formateSeconds (endTime) { 2 let secondTime = parseInt(endTime); //将传入的秒的值转化为Number 3 let min = 0; // 初始化分 4 let h = 0; // 初始化小时 5 let result = ""; 6 if (secondTime > 60) { 7 //如果秒数大于60,将秒数转换成整数 8 min = parseInt(secondTime / 60); //获取分钟,除以60取整数,得到整数分钟 9 secondTime = parseInt(secondTime % 60); //获取秒数,秒数取佘,得到整数秒数 10 if (min > 60) { 11 //如果分钟大于60,将分钟转换成小时 12 h = parseInt(min / 60); //获取小时,获取分钟除以60,得到整数小时 13 min = parseInt(min % 60); //获取小时后取佘的分,获取分钟除以60取佘的分 14 } 15 } 16 result = `${h.toString().padStart(2, "0")}:${min.toString().padStart(2, "0")}:${secondTime.toString().padStart(2, "0")}`; 17 return result; 18 }
将时分秒化为秒
1function formSeconds (times) { 2 let arr = times.split(":"); 3 let s = arr[2]; 4 let m = arr[1]; 5 let h = arr[0]; 6 let m1 = m<10?m.replace(/\b(0+)/gi,""):m; 7 let h1 = h<10?h.replace(/\b(0+)/gi,""):h; 8 return m1*60+Number(h1)+Number(s) 9} 10
对象深层遍历
1var obj = { 2 a:{ 3 b:{ 4 c:"maomin" 5 } 6 } 7 } 8const safeGet = (obj, path) => { 9 try { 10 return path.split('.').reduce((o, k) => o[k], obj) 11 } catch (e) { 12 return undefined 13 } 14 } 15console.log(safeGet(obj,'a.b.c'));// maomin 16
带有分割符的字符串转化成一个n维数组
1 var str = "A-2-12"; 2 var str1 = str.split('-'); 3 var arr = str1.reverse().reduce((pre,cur,i) => { 4 if(i==0) 5 { pre.push(cur) 6 return pre 7 } 8 return [cur,pre] 9},[]) 10console.log(arr) // ["A"["B",["C"]]]
获取时间戳
1 function thedata(d){ 2 return d.replace(/\-/g, "\/") 3 } 4 var serverTime = parseInt(new Date(thedata('2020-08-12 15:52:11')).valueOf()); 5 console.log(serverTime); // 1597218731000,获取到时间戳
对象深拷贝
1function deepClone(target) { 2 // 定义一个变量 3 let result; 4 // 如果当前需要深拷贝的是一个对象的话 5 if (typeof target === 'object') { 6 // 如果是一个数组的话 7 if (Array.isArray(target)) { 8 result = []; // 将result赋值为一个数组,并且执行遍历 9 for (let i in target) { 10 // 递归克隆数组中的每一项 11 result.push(deepClone(target[i])) 12 } 13 // 判断如果当前的值是null的话;直接赋值为null 14 } else if(target===null) { 15 result = null; 16 // 判断如果当前的值是一个RegExp对象的话,直接赋值 17 } else if(target.constructor===RegExp){ 18 result = target; 19 }else { 20 // 否则是普通对象,直接for in循环,递归赋值对象的所有值 21 result = {}; 22 for (let i in target) { 23 result[i] = deepClone(target[i]); 24 } 25 } 26 // 如果不是对象的话,就是基本数据类型,那么直接赋值 27 } else { 28 result = target; 29 } 30 // 返回最终结果 31 return result; 32} 33
简易版对象拷贝
1 function copy(obj) { 2 if(typeof obj == "object") { //判断是否复杂类型 3 var result = obj.constructor == Array ? [] : {};//判断数组类型或是object,数组即result=[],object即result={} 4 for(let i in obj) { 5 result[i] = typeof obj[i] == "object" ? copy(obj[i]) : obj[i]//判断数据每一项是否是object 6 } 7 } else { 8 var result = obj //基本类型直接拷贝 9 } 10 return result; 11}
实现一个模板引擎
1function render(template, data) { 2 const reg = /\{\{(\w+)\}\}/; // 模板字符串正则 3 if (reg.test(template)) { // 判断模板里是否有模板字符串 4 const name = reg.exec(template)[1]; // 查找当前模板里第一个模板字符串的字段 5 template = template.replace(reg, data[name]); // 将第一个模板字符串渲染 6 return render(template, data); // 递归的渲染并返回渲染后的结构 7 } 8 return template; // 如果模板没有模板字符串直接返回 9} 10let template = '我是{{name}},年龄{{age}},性别{{sex}}'; 11let data = { 12 name: '姓名', 13 age: 18 14} 15render(template, data); // 我是姓名,年龄18,性别undefined 16
节流
1// ①定时器实现 2const throttle = (fn,delay = 500) =>{ 3 let flag = true; 4 return (...args) => { 5 if(!flag) return; 6 flag = false; 7 setTimeout(() => { 8 fn.apply(this,args); 9 flag = true; 10 },delay); 11 }; 12} 13// ②时间戳实现 14const throttle = (fn,delay = 500) => { 15 let preTime = Date.now(); 16 return (...args) => { 17 const nowTime = Date.now(); 18 if(nowTime - preTime >= delay){ 19 preTime = Date.now(); 20 fn.apply(this,args); 21 } 22 } 23} 24
封装fetch
1/** 2 * 封装fetch函数,用Promise做回调 3 * @type {{get: (function(*=)), post: (function(*=, *=))}} 4 */ 5const fetchUtil = { 6 get: (url) => { 7 return new Promise((resolve, reject) => { 8 fetch(url, { 9 method: 'GET', 10 headers: { 11 'Content-Type': 'application/x-www-form-urlencoded', 12 } 13 }).then((response) => response.json()).then(response => { 14 resolve(response); 15 }).catch(err => { 16 reject(new Error(err)); 17 }); 18 }); 19 }, 20 post: (url, params) => { 21 return new Promise((resolve, reject) => { 22 fetch(url, { 23 method: 'POST', 24 headers: { 25 'Content-Type': 'application/x-www-form-urlencoded', 26 }, 27 body: params 28 }).then((response) => response.json()).then(response => { 29 resolve(response); 30 }).catch(err => { 31 reject(new Error(err)); 32 }); 33 }); 34 } 35}; 36
判断浏览器环境
1function getSystem(){ 2 const mac = /mac/i, 3 linux = /linux/i, 4 win = /win/i; 5 const platform = navigator.platform.toLowerCase(); 6 if(mac.test(platform)){ 7 return 'MAC'; 8 } else if(win.test(platform)){ 9 return 'WIN'; 10 } else if(linux.test(platform)){ 11 return 'Linux'; 12 } 13 return undefined; 14} 15const browser = { 16 versions:function(){ 17 let ret = 'xxSys'; 18 const u = navigator.userAgent; 19 const isMobile = !!u.match(/AppleWebKit.*Mobile.*/), 20 ios = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), 21 android = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; 22 if(isMobile){ 23 if(ios) return 'IOS'; 24 if(android) return 'Android'; 25 } else { 26 ret = getSystem() || ret; 27 } 28 return ret; 29 }(), 30}; 31
定义数组内部对象形式
1const objArrtransArr = (olddata, oldval, oldname)=>{ 2 const newArr = []; 3 olddata.forEach(item => { 4 // 定义数组内部对象形式 5 let obj = {}; 6 obj.value = item[oldval]; 7 obj.name = item[oldname]; 8 // 将对象数据推到数组中 9 newArr.push(obj); 10 }); 11 return newArr; 12} 13
解析html字符串
1function (htmlobj) { 2 var el = document.createElement('div'); 3 el.innerHTML = htmlobj; 4 var tags = el.getElementsByTagName('img'); 5 var text = tags[0].getAttribute("src"); 6 return text; 7} 8
判断浏览器是否支持摄像头
1function videoCheck () { 2 var deviceList = []; 3 navigator.mediaDevices 4 .enumerateDevices() 5 .then(devices => { 6 devices.forEach(device => { 7 deviceList.push(device.kind); 8 }); 9 if (deviceList.indexOf("videoinput") == "-1") { 10 console.info("没有摄像头"); 11 return false; 12 } else { 13 console.info("有摄像头"); 14 } 15 }) 16 .catch(function(err) { 17 alert(err.name + ": " + err.message); 18 }); 19 } 20
回文算法
1 //忽略标点符号、大小写和空格,正着读和反着读一模一样。 2function made(str) { 3 var str1 = str.toLowerCase(); //先将字符串全部转换为小写 4 var reg = /[\W\_]/g; // 删除所有非字母数字字符和下划线 5 var str2 = str1.replace(reg, ""); // 去掉非字母和非数字 6 var str3 = str2.split(""); // 字符串分隔成数组 7 var str4 = str3.reverse(); // 反转数组中的元素 8 var str5 = str4.join(""); // 反转后的数组转化为字符串 9 return str2 === str5; 10}
持续更新...
结语
欢迎关注我的公众号前端历劫之路
回复关键词电子书,即可获取12本前端热门电子书。
回复关键词红宝书第4版,即可获取最新《JavaScript高级程序设计》(第四版)电子书。
关注公众号后,点击下方菜单即可加我微信,我拉拢了很多IT大佬,创建了一个技术交流、文章分享群,期待你的加入。
- END -

本文转转自微信公众号前端历劫之路原创https://mp.weixin.qq.com/s/R2q8swcbdF5uVAKWS-5Gyw,如有侵权,请联系删除。

