56个实用的JavaScript 工具函数助你提升开发效率
程序员文章站
2022-03-21 08:32:21
目录(1)存储loalstorage(2)获取localstorage(3)删除localstorage(4)存储sessionstorage(5)获取sessionstorage(6)删除sessi...
实用工具函数:
1. 数字操作
(1)生成指定范围随机数
(2)数字千分位分隔
export const format = (n) => { let num = n.tostring(); let len = num.length; if (len <= 3) { return num; } else { let temp = ''; let remainder = len % 3; if (remainder > 0) { // 不是3的整数倍 return num.slice(0, remainder) + ',' + num.slice(remainder, len).match(/\d{3}/g).join(',') + temp; } else { // 3的整数倍 return num.slice(0, len).match(/\d{3}/g).join(',') + temp; } } }
2. 数组操作
(1)数组乱序
export const arrscrambling = (arr) => { for (let i = 0; i < arr.length; i++) { const randomindex = math.round(math.random() * (arr.length - 1 - i)) + i; [arr[i], arr[randomindex]] = [arr[randomindex], arr[i]]; } return arr; }
(2)数组扁平化
export const flatten = (arr) => { let result = []; for(let i = 0; i < arr.length; i++) { if(array.isarray(arr[i])) { result = result.concat(flatten(arr[i])); } else { result.push(arr[i]); } } return result; }
(3)数组中获取随机数
export const sample = arr => arr[math.floor(math.random() * arr.length)];
3. 字符串操作
(1)生成随机字符串
export const randomstring = (len) => { let chars = 'abcdefghjkmnpqrstwxyzabcdefhijkmnprstwxyz123456789'; let strlen = chars.length; let randomstr = ''; for (let i = 0; i < len; i++) { randomstr += chars.charat(math.floor(math.random() * strlen)); } return randomstr; };
(2)字符串首字母大写
export const fistletterupper = (str) => { return str.charat(0).touppercase() + str.slice(1); };
(3)手机号中间四位变成*
export const telformat = (tel) => { tel = string(tel); return tel.substr(0,3) + "****" + tel.substr(7); };
(4)驼峰命名转换成短横线命名
export const getkebabcase = (str) => { return str.replace(/[a-z]/g, (item) => '-' + item.tolowercase()) }
(5)短横线命名转换成驼峰命名
export const getcamelcase = (str) => { return str.replace( /-([a-z])/g, (i, item) => item.touppercase()) }
(6)全角转换为半角
export const tocdb = (str) => { let result = ""; for (let i = 0; i < str.length; i++) { code = str.charcodeat(i); if (code >= 65281 && code <= 65374) { result += string.fromcharcode(str.charcodeat(i) - 65248); } else if (code == 12288) { result += string.fromcharcode(str.charcodeat(i) - 12288 + 32); } else { result += str.charat(i); } } return result; }
(7)半角转换为全角
export const todbc = (str) => { let result = ""; for (let i = 0; i < str.length; i++) { code = str.charcodeat(i); if (code >= 33 && code <= 126) { result += string.fromcharcode(str.charcodeat(i) + 65248); } else if (code == 32) { result += string.fromcharcode(str.charcodeat(i) + 12288 - 32); } else { result += str.charat(i); } } return result; }
4. 格式转化
(1)数字转化为大写金额
export const digituppercase = (n) => { const fraction = ['角', '分']; const digit = [ '零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖' ]; const unit = [ ['元', '万', '亿'], ['', '拾', '佰', '仟'] ]; n = math.abs(n); let s = ''; for (let i = 0; i < fraction.length; i++) { s += (digit[math.floor(n * 10 * math.pow(10, i)) % 10] + fraction[i]).replace(/零./, ''); } s = s || '整'; n = math.floor(n); for (let i = 0; i < unit[0].length && n > 0; i++) { let p = ''; for (let j = 0; j < unit[1].length && n > 0; j++) { p = digit[n % 10] + unit[1][j] + p; n = math.floor(n / 10); } s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s; } return s.replace(/(零.)*零元/, '元') .replace(/(零.)+/g, '零') .replace(/^整$/, '零元整'); };
(2)数字转化为中文数字
export const inttochinese = (value) => { const str = string(value); const len = str.length-1; const idxs = ['','十','百','千','万','十','百','千','亿','十','百','千','万','十','百','千','亿']; const num = ['零','一','二','三','四','五','六','七','八','九']; return str.replace(/([1-9]|0+)/g, ( $, $1, idx, full) => { let pos = 0; if($1[0] !== '0'){ pos = len-idx; if(idx == 0 && $1[0] == 1 && idxs[len-idx] == '十'){ return idxs[len-idx]; } return num[$1[0]] + idxs[len-idx]; } else { let left = len - idx; let right = len - idx + $1.length; if(math.floor(right / 4) - math.floor(left / 4) > 0){ pos = left - left % 4; } if( pos ){ return idxs[pos] + num[$1[0]]; } else if( idx + $1.length >= len ){ return ''; }else { return num[$1[0]] } } }); }
5. 操作存储
(1)存储loalstorage
export const loalstorageset = (key, value) => { if (!key) return; if (typeof value !== 'string') { value = json.stringify(value); } window.localstorage.setitem(key, value); };
(2)获取localstorage
export const loalstorageget = (key) => { if (!key) return; return window.localstorage.getitem(key); };
(3)删除localstorage
export const loalstorageremove = (key) => { if (!key) return; window.localstorage.removeitem(key); };
(4)存储sessionstorage
export const sessionstorageset = (key, value) => { if (!key) return; if (typeof value !== 'string') { value = json.stringify(value); } window.sessionstorage.setitem(key, value) };
(5)获取sessionstorage
export const sessionstorageget = (key) => { if (!key) return; return window.sessionstorage.getitem(key) };
(6)删除sessionstorage
export const sessionstorageremove = (key) => { if (!key) return; window.sessionstorage.removeitem(key) };
6. 操作cookie
(1)设置cookie
export const setcookie = (key, value, expire) => { const d = new date(); d.setdate(d.getdate() + expire); document.cookie = `${key}=${value};expires=${d.toutcstring()}` };
(2)读取cookie
export const getcookie = (key) => { const cookiestr = unescape(document.cookie); const arr = cookiestr.split('; '); let cookievalue = ''; for (let i = 0; i < arr.length; i++) { const temp = arr[i].split('='); if (temp[0] === key) { cookievalue = temp[1]; break } } return cookievalue };
(3)删除cookie
export const delcookie = (key) => { document.cookie = `${encodeuricomponent(key)}=;expires=${new date()}` };
7. 格式校验
(1)校验身份证号码
export const checkcardno = (value) => { let reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|x|x)$)/; return reg.test(value); };
(2)校验是否包含中文
export const havecnchars => (value) => { return /[\u4e00-\u9fa5]/.test(value); }
(3)校验是否为*的邮政编码
export const ispostcode = (value) => { return /^[1-9][0-9]{5}$/.test(value.tostring()); }
(4)校验是否为ipv6地址
export const isipv6 = (str) => { return boolean(str.match(/:/g)?str.match(/:/g).length<=7:false && /::/.test(str)?/^([\da-f]{1,4}(:|::)){1,6}[\da-f]{1,4}$/i.test(str):/^([\da-f]{1,4}:){7}[\da-f]{1,4}$/i.test(str)); }
(5)校验是否为邮箱地址
export const isemail = (value) { return /^[a-za-z0-9_-]+@[a-za-z0-9_-]+(\.[a-za-z0-9_-]+)+$/.test(value); }
(6)校验是否为*手机号
export const istel = (value) => { return /^1[3,4,5,6,7,8,9][0-9]{9}$/.test(value.tostring()); }
(7)校验是否包含emoji表情
export const isemojicharacter = (value) => { value = string(value); for (let i = 0; i < value.length; i++) { const hs = value.charcodeat(i); if (0xd800 <= hs && hs <= 0xdbff) { if (value.length > 1) { const ls = value.charcodeat(i + 1); const uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000; if (0x1d000 <= uc && uc <= 0x1f77f) { return true; } } } else if (value.length > 1) { const ls = value.charcodeat(i + 1); if (ls == 0x20e3) { return true; } } else { if (0x2100 <= hs && hs <= 0x27ff) { return true; } else if (0x2b05 <= hs && hs <= 0x2b07) { return true; } else if (0x2934 <= hs && hs <= 0x2935) { return true; } else if (0x3297 <= hs && hs <= 0x3299) { return true; } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) { return true; } } } return false; }
8. 操作url
(1)获取url参数列表
export const getrequest = () => { let url = location.search; const paramsstr = /.+\?(.+)$/.exec(url)[1]; // 将 ? 后面的字符串取出来 const paramsarr = paramsstr.split('&'); // 将字符串以 & 分割后存到数组中 let paramsobj = {}; // 将 params 存到对象中 paramsarr.foreach(param => { if (/=/.test(param)) { // 处理有 value 的参数 let [key, val] = param.split('='); // 分割 key 和 value val = decodeuricomponent(val); // 解码 val = /^\d+$/.test(val) ? parsefloat(val) : val; // 判断是否转为数字 if (paramsobj.hasownproperty(key)) { // 如果对象有 key,则添加一个值 paramsobj[key] = [].concat(paramsobj[key], val); } else { // 如果对象没有这个 key,创建 key 并设置值 paramsobj[key] = val; } } else { // 处理没有 value 的参数 paramsobj[param] = true; } }) return paramsobj; };
(2)检测url是否有效
export const geturlstate = (url) => { let xmlhttp = new activexobject("microsoft.xmlhttp"); xmlhttp.open("get", url, false); try { xmlhttp.send(); } catch (e) { } finally { let result = xmlhttp.responsetext; if (result) { if (xmlhttp.status == 200) { return true; } else { return false; } } else { return false; } } }
(3)键值对拼接成url参数
export const params2url = (obj) => { let params = [] for (let key in obj) { params.push(`${key}=${obj[key]}`); } return encodeuricomponent(params.join('&')) }
(4)修改url中的参数
export const replaceparamval => (paramname, replacewith) { const ourl = location.href.tostring(); const re = eval('/('+ paramname+'=)([^&]*)/gi'); location.href = ourl.replace(re,paramname+'='+replacewith); return location.href; }
(5)删除url中指定参数
export const funcurldel = (name) => { const baseurl = location.origin + location.pathname + "?"; const query = location.search.substr(1); if (query.indexof(name) > -1) { const obj = {}; const arr = query.split("&"); for (let i = 0; i < arr.length; i++) { arr[i] = arr[i].split("="); obj[arr[i][0]] = arr[i][1]; } delete obj[name]; return baseurl + json.stringify(obj).replace(/[\"\{\}]/g,"").replace(/\:/g,"=").replace(/\,/g,"&"); } }
9. 设备判断
(1)判断是移动还是pc设备
export const ismobile = () => { if ((navigator.useragent.match(/(iphone|ipod|android|ios|ios|ipad|backerry|webos|symbian|windows phone|phone)/i))) { return 'mobile'; } return 'desktop'; }
(2)判断是否是苹果还是安卓移动设备
export const isapplemobiledevice = () => { let reg = /iphone|ipod|ipad|macintosh/i; return reg.test(navigator.useragent.tolowercase()); }
(3)判断是否是安卓移动设备
export const isandroidmobiledevice = () => { return /android/i.test(navigator.useragent.tolowercase()); }
(4)判断是windows还是mac系统
export const ostype = () => { const agent = navigator.useragent.tolowercase(); const ismac = /macintosh|mac os x/i.test(navigator.useragent); const iswindows = agent.indexof("win64") >= 0 || agent.indexof("wow64") >= 0 || agent.indexof("win32") >= 0 || agent.indexof("wow32") >= 0; if (iswindows) { return "windows"; } if(ismac){ return "mac"; } }
(5)判断是否是微信/qq内置浏览器
export const broswer = () => { const ua = navigator.useragent.tolowercase(); if (ua.match(/micromessenger/i) == "micromessenger") { return "weixin"; } else if (ua.match(/qq/i) == "qq") { return "qq"; } return false; }
(6)浏览器型号和版本
export const getexplorerinfo = () => { let t = navigator.useragent.tolowercase(); return 0 <= t.indexof("msie") ? { //ie < 11 type: "ie", version: number(t.match(/msie ([\d]+)/)[1]) } : !!t.match(/trident\/.+?rv:(([\d.]+))/) ? { // ie 11 type: "ie", version: 11 } : 0 <= t.indexof("edge") ? { type: "edge", version: number(t.match(/edge\/([\d]+)/)[1]) } : 0 <= t.indexof("firefox") ? { type: "firefox", version: number(t.match(/firefox\/([\d]+)/)[1]) } : 0 <= t.indexof("chrome") ? { type: "chrome", version: number(t.match(/chrome\/([\d]+)/)[1]) } : 0 <= t.indexof("opera") ? { type: "opera", version: number(t.match(/opera.([\d]+)/)[1]) } : 0 <= t.indexof("safari") ? { type: "safari", version: number(t.match(/version\/([\d]+)/)[1]) } : { type: t, version: -1 } }
10. 浏览器操作
(1)滚动到页面顶部
export const scrolltotop = () => { const height = document.documentelement.scrolltop || document.body.scrolltop; if (height > 0) { window.requestanimationframe(scrolltotop); window.scrollto(0, height - height / 8); } }
(2)滚动到页面底部
export const scrolltobottom = () => { window.scrollto(0, document.documentelement.clientheight); }
(3)滚动到指定元素区域
export const smoothscroll = (element) => { document.queryselector(element).scrollintoview({ behavior: 'smooth' }); };
(4)获取可视窗口高度
export const getclientheight = () => { let clientheight = 0; if (document.body.clientheight && document.documentelement.clientheight) { clientheight = (document.body.clientheight < document.documentelement.clientheight) ? document.body.clientheight : document.documentelement.clientheight; } else { clientheight = (document.body.clientheight > document.documentelement.clientheight) ? document.body.clientheight : document.documentelement.clientheight; } return clientheight; }
(5)获取可视窗口宽度
export const getpageviewwidth = () => { return (document.compatmode == "backcompat" ? document.body : document.documentelement).clientwidth; }
(6)打开浏览器全屏
export const tofullscreen = () => { let element = document.body; if (element.requestfullscreen) { element.requestfullscreen() } else if (element.mozrequestfullscreen) { element.mozrequestfullscreen() } else if (element.msrequestfullscreen) { element.msrequestfullscreen() } else if (element.webkitrequestfullscreen) { element.webkitrequestfullscreen() } }
(7)退出浏览器全屏
export const exitfullscreen = () => { if (document.exitfullscreen) { document.exitfullscreen() } else if (document.msexitfullscreen) { document.msexitfullscreen() } else if (document.mozcancelfullscreen) { document.mozcancelfullscreen() } else if (document.webkitexitfullscreen) { document.webkitexitfullscreen() } }
11. 时间操作
(1)当前时间
export const nowtime = () => { const now = new date(); const year = now.getfullyear(); const month = now.getmonth(); const date = now.getdate() >= 10 ? now.getdate() : ('0' + now.getdate()); const hour = now.gethours() >= 10 ? now.gethours() : ('0' + now.gethours()); const miu = now.getminutes() >= 10 ? now.getminutes() : ('0' + now.getminutes()); const sec = now.getseconds() >= 10 ? now.getseconds() : ('0' + now.getseconds()); return +year + "年" + (month + 1) + "月" + date + "日 " + hour + ":" + miu + ":" + sec; }
(2)格式化时间
export const dateformater = (formater, time) => { let date = time ? new date(time) : new date(), y = date.getfullyear() + '', m = date.getmonth() + 1, d = date.getdate(), h = date.gethours(), m = date.getminutes(), s = date.getseconds(); return formater.replace(/yyyy|yyyy/g, y) .replace(/yy|yy/g, y.substr(2, 2)) .replace(/mm/g,(m<10 ? '0' : '') + m) .replace(/dd/g,(d<10 ? '0' : '') + d) .replace(/hh|hh/g,(h<10 ? '0' : '') + h) .replace(/mm/g,(m<10 ? '0' : '') + m) .replace(/ss/g,(s<10 ? '0' : '') + s) } // dateformater('yyyy-mm-dd hh:mm:ss') // dateformater('yyyymmddhhmmss')
12. javascript操作
(1)阻止冒泡事件
export const stoppropagation = (e) => { e = e || window.event; if(e.stoppropagation) { // w3c阻止冒泡方法 e.stoppropagation(); } else { e.cancelbubble = true; // ie阻止冒泡方法 } }
(2)防抖函数
export const debounce = (fn, wait) => { let timer = null; return function() { let context = this, args = arguments; if (timer) { cleartimeout(timer); timer = null; } timer = settimeout(() => { fn.apply(context, args); }, wait); }; }
(3)节流函数
export const throttle = (fn, delay) => { let curtime = date.now(); return function() { let context = this, args = arguments, nowtime = date.now(); if (nowtime - curtime >= delay) { curtime = date.now(); return fn.apply(context, args); } }; }
(4)数据类型判断
export const gettype = (value) => { if (value === null) { return value + ""; } // 判断数据是引用类型的情况 if (typeof value === "object") { let valueclass = object.prototype.tostring.call(value), type = valueclass.split(" ")[1].split(""); type.pop(); return type.join("").tolowercase(); } else { // 判断数据是基本数据类型的情况和函数的情况 return typeof value; } }
(5)对象深拷贝
export const deepclone = (obj, hash = new weakmap() => { // 日期对象直接返回一个新的日期对象 if (obj instanceof date){ return new date(obj); } //正则对象直接返回一个新的正则对象 if (obj instanceof regexp){ return new regexp(obj); } //如果循环引用,就用 weakmap 来解决 if (hash.has(obj)){ return hash.get(obj); } // 获取对象所有自身属性的描述 let alldesc = object.getownpropertydescriptors(obj); // 遍历传入参数所有键的特性 let cloneobj = object.create(object.getprototypeof(obj), alldesc) hash.set(obj, cloneobj) for (let key of reflect.ownkeys(obj)) { if(typeof obj[key] === 'object' && obj[key] !== null){ cloneobj[key] = deepclone(obj[key], hash); } else { cloneobj[key] = obj[key]; } } return cloneobj }
到此这篇关于56个实用的javascript 工具函数助你提升开发效率的文章就介绍到这了,更多相关56个实用的javascript 工具函数内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
上一篇: 分布式锁之Redis篇