这些JS工具函数够你用到2020年底了

开发 开发工具
本篇给大家介绍JS工具函数,希望对你有所帮助。活不多说,自己平时搜集的干货函数奉上。

[[356182]]

 前言

活不多说,自己平时搜集的干货函数奉上。

干货函数

找出数字在数组中下一个相邻的元素

  1. let i = ""
  2. let rr = []; 
  3.  
  4. const 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.  
  17. let arr = ["2""4""6""8""10""12""14""16""18""20""22""24""27""30""33""36""42""48""54""60"
  18. console.log(name('5',arr)); //4 

格式化时间

  1. /** 
  2.  * @param {number} time 
  3.  * @param {string} option 
  4.  * @returns {string} 
  5.  */ 
  6. function formatTime(timeoption) { 
  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(timeoption
  29.   } else { 
  30.     return ( 
  31.       d.getMonth() + 
  32.       1 + 
  33.       '月' + 
  34.       d.getDate() + 
  35.       '日' + 
  36.       d.getHours() + 
  37.       '时' + 
  38.       d.getMinutes() + 
  39.       '分' 
  40.     ) 
  41.   } 

解析时间

  1. /** 
  2.  * Parse the time to string 
  3.  * @param {(Object|string|number)} time 
  4.  * @param {string} cFormat 
  5.  * @returns {string | null
  6.  */ 
  7. function 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 

解析Url地址

  1. /** 
  2.  * @param {string} url 
  3.  * @returns {Object} 
  4.  */ 
  5. function 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 

合并两个对象

  1. /** 
  2.  * Merges two objects, giving the last one precedence 
  3.  * @param {Object} target 
  4.  * @param {(Object|Array)} source 
  5.  * @returns {Object} 
  6.  */ 
  7. function 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 

数组去重

  1. /** 
  2.  * @param {Array} arr 
  3.  * @returns {Array} 
  4.  */ 
  5. function uniqueArr(arr) { 
  6.   return Array.from(new Set(arr)) 

防抖

  1. /** 
  2.  * @param {Function} func 
  3.  * @param {number} wait 
  4.  * @param {boolean} immediate 
  5.  * @return {*} 
  6.  */ 
  7. function 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.   } 

简易搜索

  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> 
  12.   let list = ["示例1","示例12","示例5","示例56"]; 
  13.   document.querySelector('#int').onchange=function(e){ 
  14.     console.log(search(e.target.value)); 
  15.   } 
  16.    
  17.   function search(val) { 
  18.     if (val) { 
  19.         return list.filter(function (item) { 
  20.           return Object.keys(item).some(function (key) { 
  21.             return String(item[key]).toLowerCase().indexOf(val) > -1 
  22.           }) 
  23.         }) 
  24.     } 
  25.     return list  
  26.   } 
  27.  
  28. </script> 
  29. </html> 

将秒化为时分秒

  1. function 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.     } 
  19.      
  20. 将时分秒化为秒 

将时分秒化为秒

  1. function 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) 

对象深层遍历

  1. var obj = { 
  2.   a:{ 
  3.    b:{ 
  4.     c:"maomin" 
  5.    } 
  6.   } 
  7.  } 
  8. const safeGet = (obj, path) => { 
  9.         try { 
  10.           return path.split('.').reduce((o, k) => o[k], obj) 
  11.         } catch (e) { 
  12.           return undefined 
  13.         } 
  14.     } 
  15. console.log(safeGet(obj,'a.b.c'));// maomin 

带有分割符的字符串转化成一个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. },[]) 
  10. console.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,获取到时间戳 

对象深拷贝

  1. function 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; 

简易版对象拷贝

  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; 

实现一个模板引擎

  1. function 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. let template = '我是{{name}},年龄{{age}},性别{{sex}}'
  10. let data = { 
  11.   name'姓名'
  12.   age: 18 
  13. render(template, data); // 我是姓名,年龄18,性别undefined 

节流

  1. // ①定时器实现 
  2. const 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. const throttle = (fn,delay = 500) => { 
  14.   let preTime = Date.now(); 
  15.   return (...args) => { 
  16.     const nowTime = Date.now(); 
  17.     if(nowTime - preTime >= delay){ 
  18.        preTime = Date.now(); 
  19.        fn.apply(this,args); 
  20.     } 
  21.   } 

封装fetch

  1. /** 
  2.  * 封装fetch函数,用Promise做回调 
  3.  * @type {{get: (function(*=)), post: (function(*=, *=))}} 
  4.  */ 
  5. const 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. }; 

判断浏览器环境

  1. function 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. const browser = {  
  15.     versions:function(){  
  16.         let ret = 'xxSys'
  17.         const u = navigator.userAgent; 
  18.         const isMobile = !!u.match(/AppleWebKit.*Mobile.*/), 
  19.             ios = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), 
  20.             android = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; 
  21.         if(isMobile){ 
  22.             if(ios) return 'IOS'
  23.             if(android) return 'Android'
  24.         } else { 
  25.             ret = getSystem() || ret; 
  26.         } 
  27.         return ret; 
  28.     }(), 
  29. }; 

定义数组内部对象形式

  1. const 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; 

解析html字符串

  1. function (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; 

判断浏览器是否支持摄像头

  1. function 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.     } 

回文算法

  1. //忽略标点符号、大小写和空格,正着读和反着读一模一样。 
  2. nction 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; 

持续更新...

 

责任编辑:姜华 来源: 前端历劫之路
相关推荐

2021-06-06 16:52:11

工具函数JS

2016-12-30 13:31:30

大数据盘点

2021-04-04 22:42:52

5G北美网络

2010-05-10 12:08:53

IP地址

2020-11-09 07:25:20

函数 JavaScript数据

2019-12-03 10:04:18

程序员招聘开发

2010-05-24 09:07:42

2012-09-18 09:55:33

Intel英特尔CPU

2009-10-26 09:50:46

WiMAX2802.16

2013-07-23 09:36:36

商用LTE4G

2019-12-30 18:28:39

人工智能机器人微软

2012-06-25 09:25:22

惠普裁员

2009-01-12 21:51:07

CCNP证书北漂求职

2021-10-14 11:06:53

物联网通信技术

2021-03-09 19:44:33

中国电信5G网络

2017-09-28 11:04:10

神器

2018-07-10 09:36:25

2009-11-20 08:48:15

Chrome上市时间

2009-11-20 09:10:58

Chrome OS收费模式

2022-02-20 07:37:03

网络犯罪加密货币黑客攻击
点赞
收藏

51CTO技术栈公众号