- 178.如何获得两个日期之间的差异(以天为单位)?
- 179.如何向传递的URL发出GET请求?
- 180.如何对传递的URL发出POST请求?
- 181.如何为指定选择器创建具有指定范围,步长和持续时间的计数器?
- 182.如何将字符串复制到剪贴板?
- 183.如何确定页面的浏览器选项卡是否聚焦?
- 184.如何创建目录(如果不存在)?
- 185.日期型函数封装
- 186.时间戳转时间
- 187.js中获取上下文路径
- 188.JS大小转化B KB MB GB的转化方法
- 189.js全屏和退出全屏
- 190.格式化时间,转化为几分钟前,几秒钟前
- 191. 获取n天之前的日期 getDaysBeforeDate(10) 10天前
- 192.获取跳转的classId,通过hash方式获取
- 193.过滤器指定字段
- 194.根据身份证获取出生年月
- 195.根据身份证获取年龄
- 196.原生js滑块验证
- 197.纯 js无限加载瀑布(原创)
- 198.jQuery两个元素比较高度
- 199.js定时清除缓存,存储缓存,获取缓存
- 200.数组降维
- 201.设置cookie,获取cookie,删除cookie
- 202.判读是否为外链
- 203.校验密码是否小于6位
- 204.判断是否为数字
- 205.判断是否为名称
- 206.判断是否为IP
- 207.判断是否是传统网站
- 208.判断是否是小写字母
- 209.判断是否是大写字母
- 210.判断是否是大写字母开头
- 211.判断是否是字符串
- 212.判断是否是数组
- 213.判断是否是端口号
- 214.判断是否是手机号
- 215.判断是否是邮箱
- 216.判断是否是中文
- 217.判断是否为空
- 218.判断是否为固话
- 219.判断是否为数字且最多两位小数
- 220.判断经度 -180.0~+180.0(整数部分为0~180,必须输入1到5位小数)
- 221.判断纬度 -90.0~+90.0(整数部分为0~90,必须输入1到5位小数)
- 222.rtsp校验只要有rtsp://
- 223.判断IE浏览器版本和检测是否为非IE浏览器
- 224.数组去重
文章摘自269个工具函数库:269个工具函数库下
178.如何获得两个日期之间的差异(以天为单位)?
const getDaysDiffBetweenDates = (dateInitial, dateFinal) =>(dateFinal - dateInitial) / (1000 * 3600 * 24);// 事例getDaysDiffBetweenDates(new Date('2017-12-13'), new Date('2017-12-22')); // 9
179.如何向传递的URL发出GET请求?
const httpGet = (url, callback, err = console.error) => {const request = new XMLHttpRequest();request.open('GET', url, true);request.onload = () => callback(request.responseText);request.onerror = () => err(request);request.send();};httpGet('https://jsonplaceholder.typicode.com/posts/1',console.log);// {"userId": 1, "id": 1, "title": "sample title", "body": "my text"}
180.如何对传递的URL发出POST请求?
const httpPost = (url, data, callback, err = console.error) => {const request = new XMLHttpRequest();request.open('POST', url, true);request.setRequestHeader('Content-type', 'application/json; charset=utf-8');request.onload = () => callback(request.responseText);request.onerror = () => err(request);request.send(data);};const newPost = {userId: 1,id: 1337,title: 'Foo',body: 'bar bar bar'};const data = JSON.stringify(newPost);httpPost('https://jsonplaceholder.typicode.com/posts',data,console.log);// {"userId": 1, "id": 1337, "title": "Foo", "body": "bar bar bar"}
181.如何为指定选择器创建具有指定范围,步长和持续时间的计数器?
const counter = (selector, start, end, step = 1, duration = 2000) => {let current = start,_step = (end - start) * step < 0 ? -step : step,timer = setInterval(() => {current += _step;document.querySelector(selector).innerHTML = current;if (current >= end) document.querySelector(selector).innerHTML = end;if (current >= end) clearInterval(timer);}, Math.abs(Math.floor(duration / (end - start))));return timer;};// 事例counter('#my-id', 1, 1000, 5, 2000);// 让 `id=“my-id”`的元素创建一个2秒计时器
182.如何将字符串复制到剪贴板?
const el = document.createElement('textarea');el.value = str;el.setAttribute('readonly', '');el.style.position = 'absolute';el.style.left = '-9999px';document.body.appendChild(el);const selected =document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false;el.select();document.execCommand('copy');document.body.removeChild(el);if (selected) {document.getSelection().removeAllRanges();document.getSelection().addRange(selected);}};// 事例copyToClipboard('Lorem ipsum');// 'Lorem ipsum' copied to clipboard
183.如何确定页面的浏览器选项卡是否聚焦?
const isBrowserTabFocused = () => !document.hidden;// 事例isBrowserTabFocused(); // true
184.如何创建目录(如果不存在)?
const fs = require('fs');const createDirIfNotExists = dir => (!fs.existsSync(dir) ? fs.mkdirSync(dir) : undefined);// 事例createDirIfNotExists('test');这里面的方法大都挺实用,可以解决很多开发过程问题,大家就好好利用起来吧。
185.日期型函数封装
function formatTime(date) {if(!!date){if(!(date instanceof Date))date = new Date(date);var month = date.getMonth() + 1var day = date.getDate()return `${month}月${day}日`;}}function formatDay(date) {if(!!date){var year = date.getFullYear()var month = date.getMonth() + 1var day = date.getDate()return [year, month, day].map(formatNumber).join('-');}}function formatDay2(date) {if(!!date){var year = date.getFullYear()var month = date.getMonth() + 1var day = date.getDate()return [year, month, day].map(formatNumber).join('/');}}function formatWeek(date){if(!!date){var day = date.getDay();switch (day) {case 0:return '周日'break;case 1:return '周一'break;case 2:return '周二'break;case 3:return '周三'break;case 4:return '周四'break;case 5:return '周五'break;case 6:return '周六'break;}}}function formatHour(date){if(!!date){var hour = new Date(date).getHours();var minute = new Date(date).getMinutes();return [hour, minute].map(formatNumber).join(':');}}function timestamp(date, divisor=1000){if(date == undefined){return;}else if(typeof date == 'number'){return Math.floor(date/divisor);}else if(typeof date == 'string'){var strs = date.split(/[^0-9]/);return Math.floor(+new Date(strs[0] || 0,(strs[1] || 0)-1,strs[2] || 0,strs[3] || 0,strs[4] || 0,strs[5] || 0)/divisor);}else if(Date.prototype.isPrototypeOf(date)){return Math.floor(+date/divisor);}}function detimestamp(date){if(!!date){return new Date(date*1000);}}function formatNumber(n) {//给在0-9的日期加上0n = n.toString()return n[1] ? n : '0' + n}module.exports = {formatTime: formatTime,formatDay: formatDay,formatDay2: formatDay2,formatHour: formatHour,formatWeek: formatWeek,timestamp: timestamp,detimestamp: detimestamp}
186.时间戳转时间
/*** 时间戳转化为年 月 日 时 分 秒* number: 传入时间戳* format:返回格式,支持自定义,但参数必须与formateArr里保持一致*/function formatTime(number,format) {var formateArr = ['Y','M','D','h','m','s'];var returnArr = [];var date = new Date(number * 1000);returnArr.push(date.getFullYear());returnArr.push(formatNumber(date.getMonth() + 1));returnArr.push(formatNumber(date.getDate()));returnArr.push(formatNumber(date.getHours()));returnArr.push(formatNumber(date.getMinutes()));returnArr.push(formatNumber(date.getSeconds()));for (var i in returnArr){format = format.replace(formateArr[i], returnArr[i]);}return format;}//数据转化function formatNumber(n) {n = n.toString()return n[1] ? n : '0' + n}调用示例:var sjc = 1488481383;//时间戳console.log(time.formatTime(sjc,'Y/M/D h:m:s'));//转换为日期:2017/03/03 03:03:03console.log(time.formatTime(sjc, 'h:m'));//转换为日期:03:03
187.js中获取上下文路径
js中获取上下文路径//js获取项目根路径,如: http://localhost:8083/uimcardprjfunction getRootPath(){//获取当前网址,如: http://localhost:8083/uimcardprj/share/meun.jspvar curWwwPath=window.document.location.href;//获取主机地址之后的目录,如: uimcardprj/share/meun.jspvar pathName=window.document.location.pathname;var pos=curWwwPath.indexOf(pathName);//获取主机地址,如: http://localhost:8083var localhostPaht=curWwwPath.substring(0,pos);//获取带"/"的项目名,如:/uimcardprjvar projectName=pathName.substring(0,pathName.substr(1).indexOf('/')+1);return(localhostPaht+projectName);}
188.JS大小转化B KB MB GB的转化方法
function conver(limit){var size = "";if( limit < 0.1 * 1024 ){ //如果小于0.1KB转化成Bsize = limit.toFixed(2) + "B";}else if(limit < 0.1 * 1024 * 1024 ){//如果小于0.1MB转化成KBsize = (limit / 1024).toFixed(2) + "KB";}else if(limit < 0.1 * 1024 * 1024 * 1024){ //如果小于0.1GB转化成MBsize = (limit / (1024 * 1024)).toFixed(2) + "MB";}else{ //其他转化成GBsize = (limit / (1024 * 1024 * 1024)).toFixed(2) + "GB";}var sizestr = size + "";var len = sizestr.indexOf("\.");var dec = sizestr.substr(len + 1, 2);if(dec == "00"){//当小数点后为00时 去掉小数部分return sizestr.substring(0,len) + sizestr.substr(len + 3,2);}return sizestr;}
189.js全屏和退出全屏
function fullScreen() {var el = document.documentElement;var rfs = el.requestFullScreen || el.webkitRequestFullScreen || el.mozRequestFullScreen || el.msRequestFullScreen;//typeof rfs != "undefined" && rfsif (rfs) {rfs.call(el);} else if (typeof window.ActiveXObject !== "undefined") {//for IE,这里其实就是模拟了按下键盘的F11,使浏览器全屏var wscript = new ActiveXObject("WScript.Shell");if (wscript != null) {wscript.SendKeys("{F11}");}}}//退出全屏function exitScreen() {var el = document;var cfs = el.cancelFullScreen || el.webkitCancelFullScreen || el.mozCancelFullScreen || el.exitFullScreen;//typeof cfs != "undefined" && cfsif (cfs) {cfs.call(el);} else if (typeof window.ActiveXObject !== "undefined") {//for IE,这里和fullScreen相同,模拟按下F11键退出全屏var wscript = new ActiveXObject("WScript.Shell");if (wscript != null) {wscript.SendKeys("{F11}");}}}
190.格式化时间,转化为几分钟前,几秒钟前
/*** 格式化时间,转化为几分钟前,几秒钟前* @param timestamp 时间戳,单位是毫秒*/function timeFormat(timestamp) {var mistiming = Math.round((Date.now() - timestamp) / 1000);var arrr = ['年', '个月', '星期', '天', '小时', '分钟', '秒'];var arrn = [31536000, 2592000, 604800, 86400, 3600, 60, 1];for (var i = 0; i < arrn.length; i++) {var inm = Math.floor(mistiming / arrn[i]);if (inm != 0) {return inm + arrr[i] + '前';}}}
191. 获取n天之前的日期 getDaysBeforeDate(10) 10天前
/*** 获取n天之前的日期 getDaysBeforeDate(10) 10天前* @param day 天数*/function getDaysBeforeDate(day) {var date = new Date(),timestamp, newDate;timestamp = date.getTime();// 获取三天前的日期newDate = new Date(timestamp - day * 24 * 3600 * 1000);var year = newDate.getFullYear();// 月+1是因为js中月份是按0开始的var month = newDate.getMonth() + 1;var day = newDate.getDate();if (day < 10) { // 如果日小于10,前面拼接0day = '0' + day;}if (month < 10) { // 如果月小于10,前面拼接0month = '0' + month;}return [year, month, day].join('/');}
192.获取跳转的classId,通过hash方式获取
/*** 获取跳转的classId,通过hash方式获取* @return 返回值*/$scope.getQueryString = function() {var url= {},a = '';(a = window.location.search.substr(1)) || (a = window.location.hash.split('?')[1])a.split(/&/g).forEach(function(item) {url[(item = item.split('='))[0]] = item[1];})return url}
193.过滤器指定字段
function filterArrBySex(data, name) {if (!name) {console.log(name)return data;} else {return data.filter(function(ele, index, self) {if (ele.name.includes(name)) {return ele}})}}
194.根据身份证获取出生年月
/*** 根据身份证获取出生年月* @param idCard*/function getBirthdayFromIdCard(idCard) {var birthday = "";if (idCard != null && idCard != "") {if (idCard.length == 15) {birthday = "19" + idCard.substr(6, 6);} else if (idCard.length == 18) {birthday = idCard.substr(6, 8);}birthday = birthday.replace(/(.{4})(.{2})/, "$1-$2-");}return birthday;}
195.根据身份证获取年龄
/*** 根据身份证获取年龄* @param UUserCard*/function IdCard(UUserCard) {//获取年龄var myDate = new Date();var month = myDate.getMonth() + 1;var day = myDate.getDate();var age = myDate.getFullYear() - UUserCard.substring(6, 10) - 1;if (UUserCard.substring(10, 12) < month || UUserCard.substring(10, 12) == month && UUserCard.substring(12, 14) <= day) {age++;}return age}
196.原生js滑块验证
//event.clientX:鼠标点下的点到左侧x轴的距离window.onload = function() {//事件处理 onmousedown onmousemove onmouseupvar box = document.querySelector(".box")var btn = document.querySelector(".btn")var bg = document.querySelector(".bg")var text1 = document.querySelector(".text")//封装的选择器 声明式函数可以提升// function fun(){//// }var flag = false; //标记btn.onmousedown = function(event) {var downx = event.clientX; //按下后获取的与x轴的距离btn.onmousemove = function(e) {var movex = e.clientX - downx; //滑块滑动的距离//移动的范围if (movex > 0) {this.style.left = movex + "px";bg.style.width = movex + "px";if (movex >= box.offsetWidth - 40) {//验证成功flag = truetext1.innerHTML = "验证成功"text1.style.color = "#fff"//清除事件btn.onmousedown = null;btn.onmousemove = null;}}}}//松开事件btn.onmouseup = function() {//清除事件btn.onmousemove = null;if (flag) return;this.style.left = 0;bg.style.width = 0 + "px";}}
197.纯 js无限加载瀑布(原创)
//随机[m,n]之间的整数 封装function randomNumber(m, n) {return Math.floor(Math.random() * (n - m + 1) + m);}//随机颜色 封装function randomColor() {return "rgb(" + randomNumber(0, 255) + "," + randomNumber(0, 255) + "," + randomNumber(0, 255) + ")";}//获取当前的scrollTopvar scrollTopDistance;//获取所有的ulvar uls = document.querySelectorAll("ul");var i = 0;var k = i;function waterFall() {for (i = k; i < k + 4; i++) {//创建livar li = document.createElement("li");//随机颜色li.style.backgroundColor = randomColor();//随机高度li.style.height = randomNumber(120, 400) + "px";//手动转换为字符串li.innerHTML = i + 1 + "";//插入到对应的ul中//判断哪个ul的高度低,该次创建的li就插入到此ul中var index = 0; //记录下标for (var j = 0; j < uls.length; j++) {if (uls[j].offsetHeight < uls[index].offsetHeight) {index = j;}}//将元素节点插入文档中uls[index].appendChild(li);}k = i;return uls[index].offsetHeight;}waterFall();//鼠标滚轮事件,由于右侧没有滚轮,所以使用onmousewheel事件window.onmousewheel = function() {//获取窗口的高度,要兼容浏览器var windowH = document.documentElement.clientHeight;//滚轮于top的距离,要兼容浏览器var scrollH = document.documentElement.scrollTop ||document.body.scrollTop;//获取窗口的可见高度var documentH = document.documentElement.scrollHeight ||document.body.scrollHeight;//窗口的高度 + 滚轮与顶部的距离 > 窗口的可见高度-200if (windowH + scrollH > documentH - 200) {//执行此函数waterFall()}}
198.jQuery两个元素比较高度
$(*function* () {*var* w_max = 0;*//求最大高度*$("#MenuNavigation li").each(*function* () {*var* w = $(*this*).innerWidth();w_max = w > w_max ? w : w_max;})$("#MenuNavigation li").width(w_max)*//将最大高度赋值给所有元素,*})
199.js定时清除缓存,存储缓存,获取缓存
// 封装本地存储的方法export const storage = {set: function(variable, value, ttl_ms) {var data = { value: value, expires_at: new Date(ttl_ms).getTime() };localStorage.setItem(variable.toString(), JSON.stringify(data));},get: function(variable) {var data = JSON.parse(localStorage.getItem(variable.toString()));if (data !== null) {debuggerif (data.expires_at !== null && data.expires_at < new Date().getTime()) {localStorage.removeItem(variable.toString());} else {return data.value;}}return null;},remove(key) {localStorage.removeItem(key);}}
200.数组降维
//数组降维reduceDimension(arr) {var reduced = [];for (var i = 0; i < arr.length; i++) {reduced = reduced.concat(arr[i]);}return reduced;}
201.设置cookie,获取cookie,删除cookie
var cookieUtil = {getCookie: function (name) {var arrCookie = document.cookie.split("; ");for (var i = 0; i < arrCookie.length; i++) {var cookieItem = arrCookie[i].split('=');if (cookieItem[0] == name) {return cookieItem[1];}}return undefined;},setCookie: function (name, value, expires, path, domain, secure) {var cookieText = encodeURIComponent(name) + "=" +encodeURIComponent(value);if (expires instanceof Date) {cookieText += "; expires=" + expires.toGMTString();}if (path) {cookieText += "; path=" + path;}if (domain) {cookieText += "; domain=" + domain;}if (secure) {cookieText += "; secure";}document.cookie = cookieText;},removeCookie: function (name, path, domain, secure) {this.set(name, "", new Date(0), path, domain, secure);}}
202.判读是否为外链
/*** @description 判读是否为外链* @param path* @returns {boolean}*/export function isExternal(path) {return /^(https?:|mailto:|tel:)/.test(path);}
203.校验密码是否小于6位
/*** @description 校验密码是否小于6位* @param str* @returns {boolean}*/export function isPassword(str) {return str.length >= 6;}
204.判断是否为数字
/*** @description 判断是否为数字* @param value* @returns {boolean}*/export function isNumber(value) {const reg = /^[0-9]*$/;return reg.test(value);}
205.判断是否为名称
/*** @description 判断是否是名称* @param value* @returns {boolean}*/export function isName(value) {const reg = /^[\u4e00-\u9fa5a-zA-Z0-9]+$/;return reg.test(value);}
206.判断是否为IP
/*** @description 判断是否为IP* @param ip* @returns {boolean}*/export function isIP(ip) {const reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;return reg.test(ip);}
207.判断是否是传统网站
/*** @description 判断是否是传统网站* @param url* @returns {boolean}*/export function isUrl(url) {const reg = /^(https?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/;return reg.test(url);}
208.判断是否是小写字母
/*** @description 判断是否是小写字母* @param str* @returns {boolean}*/export function isLowerCase(str) {const reg = /^[a-z]+$/;return reg.test(str);}
209.判断是否是大写字母
/*** @description 判断是否是大写字母* @param str* @returns {boolean}*/export function isUpperCase(str) {const reg = /^[A-Z]+$/;return reg.test(str);}
210.判断是否是大写字母开头
/*** @description 判断是否是大写字母开头* @param str* @returns {boolean}*/export function isAlphabets(str) {const reg = /^[A-Za-z]+$/;return reg.test(str);}
211.判断是否是字符串
/*** @description 判断是否是字符串* @param str* @returns {boolean}*/export function isString(str) {return typeof str === "string" || str instanceof String;}
212.判断是否是数组
/*** @description 判断是否是数组* @param arg* @returns {arg is any[]|boolean}*/export function isArray(arg) {if (typeof Array.isArray === "undefined") {return Object.prototype.toString.call(arg) === "[object Array]";}return Array.isArray(arg);}
213.判断是否是端口号
/*** @description 判断是否是端口号* @param str* @returns {boolean}*/export function isPort(str) {const reg = /^([0-9]|[1-9]\d|[1-9]\d{2}|[1-9]\d{3}|[1-5]\d{4}|6[0-4]\d{3}|65[0-4]\d{2}|655[0-2]\d|6553[0-5])$/;return reg.test(str);}
214.判断是否是手机号
/*** @description 判断是否是手机号* @param str* @returns {boolean}*/export function isPhone(str) {const reg = /^1\d{10}$/;return reg.test(str);}
215.判断是否是邮箱
/*** @description 判断是否是邮箱* @param str* @returns {boolean}*/export function isEmail(str) {const reg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;return reg.test(str);}
216.判断是否是中文
/*** @description 判断是否中文* @param str* @returns {boolean}*/export function isChina(str) {const reg = /^[\u4E00-\u9FA5]{2,4}$/;return reg.test(str);}
217.判断是否为空
/*** @description 判断是否为空* @param str* @returns {boolean}*/export function isBlank(str) {return (str == null ||false ||str === "" ||str.trim() === "" ||str.toLocaleLowerCase().trim() === "null");}
218.判断是否为固话
/*** @description 判断是否为固话* @param str* @returns {boolean}*/export function isTel(str) {const reg = /^(400|800)([0-9\\-]{7,10})|(([0-9]{4}|[0-9]{3})(-| )?)?([0-9]{7,8})((-| |转)*([0-9]{1,4}))?$/;return reg.test(str);}
219.判断是否为数字且最多两位小数
/*** @description 判断是否为数字且最多两位小数* @param str* @returns {boolean}*/export function isNum(str) {const reg = /^\d+(\.\d{1,2})?$/;return reg.test(str);}
220.判断经度 -180.0~+180.0(整数部分为0~180,必须输入1到5位小数)
/*** @description 判断经度 -180.0~+180.0(整数部分为0~180,必须输入1到5位小数)* @param str* @returns {boolean}*/export function isLongitude(str) {const reg = /^[-|+]?(0?\d{1,2}\.\d{1,5}|1[0-7]?\d{1}\.\d{1,5}|180\.0{1,5})$/;return reg.test(str);}
221.判断纬度 -90.0~+90.0(整数部分为0~90,必须输入1到5位小数)
/*** @description 判断纬度 -90.0~+90.0(整数部分为0~90,必须输入1到5位小数)* @param str* @returns {boolean}*/export function isLatitude(str) {const reg = /^[-|+]?([0-8]?\d{1}\.\d{1,5}|90\.0{1,5})$/;return reg.test(str);}
222.rtsp校验只要有rtsp://
/*** @description rtsp校验,只要有rtsp://* @param str* @returns {boolean}*/export function isRTSP(str) {const reg = /^rtsp:\/\/([a-z]{0,10}:.{0,10}@)?(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;const reg1 = /^rtsp:\/\/([a-z]{0,10}:.{0,10}@)?(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5]):[0-9]{1,5}/;const reg2 = /^rtsp:\/\/([a-z]{0,10}:.{0,10}@)?(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\//;return reg.test(str) || reg1.test(str) || reg2.test(str);}
223.判断IE浏览器版本和检测是否为非IE浏览器
function IEVersion() {var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串var isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1; //判断是否IE<11浏览器var isEdge = userAgent.indexOf("Edge") > -1 && !isIE; //判断是否IE的Edge浏览器var isIE11 = userAgent.indexOf('Trident') > -1 && userAgent.indexOf("rv:11.0") > -1;if (isIE) {var reIE = new RegExp("MSIE (\\d+\\.\\d+);");reIE.test(userAgent);var fIEVersion = parseFloat(RegExp["$1"]);if (fIEVersion == 7) {return 7;} else if (fIEVersion == 8) {return 8;} else if (fIEVersion == 9) {return 9;} else if (fIEVersion == 10) {return 10;} else {return 6; //IE版本<=7}} else if (isEdge) {return 'edge'; //edge} else if (isIE11) {return 11; //IE11} else {return -1; //不是ie浏览器}}
224.数组去重
方案一:Set + …
function noRepeat(arr) {return [...new Set(arr)];}noRepeat([1,2,3,1,2,3])
方案二:Set + Array.from
function noRepeat(arr) {return Array.from(new Set(arr));}noRepeat([1,2,3,1,2,3])
方案三:双重遍历比对下标
function noRepeat(arr) {return arr.filter((v, idx)=>idx == arr.lastIndexOf(v))}noRepeat([1,2,3,1,2,3])
方案四:单遍历 + Object 特性
Object 的特性是 Key 不会重复。
这里使用 values 是因为可以保留类型,keys 会变成字符串。
function noRepeat(arr) {return Object.values(arr.reduce((s,n)=>{s[n] = n;return s},{}))}noRepeat([1,2,3,1,2,3])
