文章摘自269个工具函数库:269个工具函数库下

178.如何获得两个日期之间的差异(以天为单位)?

  1. const getDaysDiffBetweenDates = (dateInitial, dateFinal) =>
  2. (dateFinal - dateInitial) / (1000 * 3600 * 24);
  3. // 事例
  4. getDaysDiffBetweenDates(new Date('2017-12-13'), new Date('2017-12-22')); // 9

179.如何向传递的URL发出GET请求?

  1. const httpGet = (url, callback, err = console.error) => {
  2. const request = new XMLHttpRequest();
  3. request.open('GET', url, true);
  4. request.onload = () => callback(request.responseText);
  5. request.onerror = () => err(request);
  6. request.send();
  7. };
  8. httpGet(
  9. 'https://jsonplaceholder.typicode.com/posts/1',
  10. console.log
  11. );
  12. // {"userId": 1, "id": 1, "title": "sample title", "body": "my text"}

180.如何对传递的URL发出POST请求?

  1. const httpPost = (url, data, callback, err = console.error) => {
  2. const request = new XMLHttpRequest();
  3. request.open('POST', url, true);
  4. request.setRequestHeader('Content-type', 'application/json; charset=utf-8');
  5. request.onload = () => callback(request.responseText);
  6. request.onerror = () => err(request);
  7. request.send(data);
  8. };
  9. const newPost = {
  10. userId: 1,
  11. id: 1337,
  12. title: 'Foo',
  13. body: 'bar bar bar'
  14. };
  15. const data = JSON.stringify(newPost);
  16. httpPost(
  17. 'https://jsonplaceholder.typicode.com/posts',
  18. data,
  19. console.log
  20. );
  21. // {"userId": 1, "id": 1337, "title": "Foo", "body": "bar bar bar"}

181.如何为指定选择器创建具有指定范围,步长和持续时间的计数器?

  1. const counter = (selector, start, end, step = 1, duration = 2000) => {
  2. let current = start,
  3. _step = (end - start) * step < 0 ? -step : step,
  4. timer = setInterval(() => {
  5. current += _step;
  6. document.querySelector(selector).innerHTML = current;
  7. if (current >= end) document.querySelector(selector).innerHTML = end;
  8. if (current >= end) clearInterval(timer);
  9. }, Math.abs(Math.floor(duration / (end - start))));
  10. return timer;
  11. };
  12. // 事例
  13. counter('#my-id', 1, 1000, 5, 2000);
  14. // 让 `id=“my-id”`的元素创建一个2秒计时器

182.如何将字符串复制到剪贴板?

  1. const el = document.createElement('textarea');
  2. el.value = str;
  3. el.setAttribute('readonly', '');
  4. el.style.position = 'absolute';
  5. el.style.left = '-9999px';
  6. document.body.appendChild(el);
  7. const selected =
  8. document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false;
  9. el.select();
  10. document.execCommand('copy');
  11. document.body.removeChild(el);
  12. if (selected) {
  13. document.getSelection().removeAllRanges();
  14. document.getSelection().addRange(selected);
  15. }
  16. };
  17. // 事例
  18. copyToClipboard('Lorem ipsum');
  19. // 'Lorem ipsum' copied to clipboard

183.如何确定页面的浏览器选项卡是否聚焦?

  1. const isBrowserTabFocused = () => !document.hidden;
  2. // 事例
  3. isBrowserTabFocused(); // true

184.如何创建目录(如果不存在)?

  1. const fs = require('fs');
  2. const createDirIfNotExists = dir => (!fs.existsSync(dir) ? fs.mkdirSync(dir) : undefined);
  3. // 事例
  4. createDirIfNotExists('test');
  5. 这里面的方法大都挺实用,可以解决很多开发过程问题,大家就好好利用起来吧。

185.日期型函数封装

  1. function formatTime(date) {
  2. if(!!date){
  3. if(!(date instanceof Date))
  4. date = new Date(date);
  5. var month = date.getMonth() + 1
  6. var day = date.getDate()
  7. return `${month}月${day}日`;
  8. }
  9. }
  10. function formatDay(date) {
  11. if(!!date){
  12. var year = date.getFullYear()
  13. var month = date.getMonth() + 1
  14. var day = date.getDate()
  15. return [year, month, day].map(formatNumber).join('-');
  16. }
  17. }
  18. function formatDay2(date) {
  19. if(!!date){
  20. var year = date.getFullYear()
  21. var month = date.getMonth() + 1
  22. var day = date.getDate()
  23. return [year, month, day].map(formatNumber).join('/');
  24. }
  25. }
  26. function formatWeek(date){
  27. if(!!date){
  28. var day = date.getDay();
  29. switch (day) {
  30. case 0:
  31. return '周日'
  32. break;
  33. case 1:
  34. return '周一'
  35. break;
  36. case 2:
  37. return '周二'
  38. break;
  39. case 3:
  40. return '周三'
  41. break;
  42. case 4:
  43. return '周四'
  44. break;
  45. case 5:
  46. return '周五'
  47. break;
  48. case 6:
  49. return '周六'
  50. break;
  51. }
  52. }
  53. }
  54. function formatHour(date){
  55. if(!!date){
  56. var hour = new Date(date).getHours();
  57. var minute = new Date(date).getMinutes();
  58. return [hour, minute].map(formatNumber).join(':');
  59. }
  60. }
  61. function timestamp(date, divisor=1000){
  62. if(date == undefined){
  63. return;
  64. }else if(typeof date == 'number'){
  65. return Math.floor(date/divisor);
  66. }else if(typeof date == 'string'){
  67. var strs = date.split(/[^0-9]/);
  68. 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);
  69. }else if(Date.prototype.isPrototypeOf(date)){
  70. return Math.floor(+date/divisor);
  71. }
  72. }
  73. function detimestamp(date){
  74. if(!!date){
  75. return new Date(date*1000);
  76. }
  77. }
  78. function formatNumber(n) {//给在0-9的日期加上0
  79. n = n.toString()
  80. return n[1] ? n : '0' + n
  81. }
  82. module.exports = {
  83. formatTime: formatTime,
  84. formatDay: formatDay,
  85. formatDay2: formatDay2,
  86. formatHour: formatHour,
  87. formatWeek: formatWeek,
  88. timestamp: timestamp,
  89. detimestamp: detimestamp
  90. }

186.时间戳转时间

  1. /**
  2. * 时间戳转化为年 月 日 时 分 秒
  3. * number: 传入时间戳
  4. * format:返回格式,支持自定义,但参数必须与formateArr里保持一致
  5. */
  6. function formatTime(number,format) {
  7. var formateArr = ['Y','M','D','h','m','s'];
  8. var returnArr = [];
  9. var date = new Date(number * 1000);
  10. returnArr.push(date.getFullYear());
  11. returnArr.push(formatNumber(date.getMonth() + 1));
  12. returnArr.push(formatNumber(date.getDate()));
  13. returnArr.push(formatNumber(date.getHours()));
  14. returnArr.push(formatNumber(date.getMinutes()));
  15. returnArr.push(formatNumber(date.getSeconds()));
  16. for (var i in returnArr)
  17. {
  18. format = format.replace(formateArr[i], returnArr[i]);
  19. }
  20. return format;
  21. }
  22. //数据转化
  23. function formatNumber(n) {
  24. n = n.toString()
  25. return n[1] ? n : '0' + n
  26. }
  27. 调用示例:
  28. var sjc = 1488481383;//时间戳
  29. console.log(time.formatTime(sjc,'Y/M/D h:m:s'));//转换为日期:2017/03/03 03:03:03
  30. console.log(time.formatTime(sjc, 'h:m'));//转换为日期:03:03

187.js中获取上下文路径

  1. js中获取上下文路径
  2. //js获取项目根路径,如: http://localhost:8083/uimcardprj
  3. function getRootPath(){
  4. //获取当前网址,如: http://localhost:8083/uimcardprj/share/meun.jsp
  5. var curWwwPath=window.document.location.href;
  6. //获取主机地址之后的目录,如: uimcardprj/share/meun.jsp
  7. var pathName=window.document.location.pathname;
  8. var pos=curWwwPath.indexOf(pathName);
  9. //获取主机地址,如: http://localhost:8083
  10. var localhostPaht=curWwwPath.substring(0,pos);
  11. //获取带"/"的项目名,如:/uimcardprj
  12. var projectName=pathName.substring(0,pathName.substr(1).indexOf('/')+1);
  13. return(localhostPaht+projectName);
  14. }

188.JS大小转化B KB MB GB的转化方法

  1. function conver(limit){
  2. var size = "";
  3. if( limit < 0.1 * 1024 ){ //如果小于0.1KB转化成B
  4. size = limit.toFixed(2) + "B";
  5. }else if(limit < 0.1 * 1024 * 1024 ){//如果小于0.1MB转化成KB
  6. size = (limit / 1024).toFixed(2) + "KB";
  7. }else if(limit < 0.1 * 1024 * 1024 * 1024){ //如果小于0.1GB转化成MB
  8. size = (limit / (1024 * 1024)).toFixed(2) + "MB";
  9. }else{ //其他转化成GB
  10. size = (limit / (1024 * 1024 * 1024)).toFixed(2) + "GB";
  11. }
  12. var sizestr = size + "";
  13. var len = sizestr.indexOf("\.");
  14. var dec = sizestr.substr(len + 1, 2);
  15. if(dec == "00"){//当小数点后为00时 去掉小数部分
  16. return sizestr.substring(0,len) + sizestr.substr(len + 3,2);
  17. }
  18. return sizestr;
  19. }

189.js全屏和退出全屏

  1. function fullScreen() {
  2. var el = document.documentElement;
  3. var rfs = el.requestFullScreen || el.webkitRequestFullScreen || el.mozRequestFullScreen || el.msRequestFullScreen;
  4. //typeof rfs != "undefined" && rfs
  5. if (rfs) {
  6. rfs.call(el);
  7. } else if (typeof window.ActiveXObject !== "undefined") {
  8. //for IE,这里其实就是模拟了按下键盘的F11,使浏览器全屏
  9. var wscript = new ActiveXObject("WScript.Shell");
  10. if (wscript != null) {
  11. wscript.SendKeys("{F11}");
  12. }
  13. }
  14. }
  15. //退出全屏
  16. function exitScreen() {
  17. var el = document;
  18. var cfs = el.cancelFullScreen || el.webkitCancelFullScreen || el.mozCancelFullScreen || el.exitFullScreen;
  19. //typeof cfs != "undefined" && cfs
  20. if (cfs) {
  21. cfs.call(el);
  22. } else if (typeof window.ActiveXObject !== "undefined") {
  23. //for IE,这里和fullScreen相同,模拟按下F11键退出全屏
  24. var wscript = new ActiveXObject("WScript.Shell");
  25. if (wscript != null) {
  26. wscript.SendKeys("{F11}");
  27. }
  28. }
  29. }

190.格式化时间,转化为几分钟前,几秒钟前

  1. /**
  2. * 格式化时间,转化为几分钟前,几秒钟前
  3. * @param timestamp 时间戳,单位是毫秒
  4. */
  5. function timeFormat(timestamp) {
  6. var mistiming = Math.round((Date.now() - timestamp) / 1000);
  7. var arrr = ['年', '个月', '星期', '天', '小时', '分钟', '秒'];
  8. var arrn = [31536000, 2592000, 604800, 86400, 3600, 60, 1];
  9. for (var i = 0; i < arrn.length; i++) {
  10. var inm = Math.floor(mistiming / arrn[i]);
  11. if (inm != 0) {
  12. return inm + arrr[i] + '前';
  13. }
  14. }
  15. }

191. 获取n天之前的日期 getDaysBeforeDate(10) 10天前

  1. /**
  2. * 获取n天之前的日期 getDaysBeforeDate(10) 10天前
  3. * @param day 天数
  4. */
  5. function getDaysBeforeDate(day) {
  6. var date = new Date(),
  7. timestamp, newDate;
  8. timestamp = date.getTime();
  9. // 获取三天前的日期
  10. newDate = new Date(timestamp - day * 24 * 3600 * 1000);
  11. var year = newDate.getFullYear();
  12. // 月+1是因为js中月份是按0开始的
  13. var month = newDate.getMonth() + 1;
  14. var day = newDate.getDate();
  15. if (day < 10) { // 如果日小于10,前面拼接0
  16. day = '0' + day;
  17. }
  18. if (month < 10) { // 如果月小于10,前面拼接0
  19. month = '0' + month;
  20. }
  21. return [year, month, day].join('/');
  22. }

192.获取跳转的classId,通过hash方式获取

  1. /**
  2. * 获取跳转的classId,通过hash方式获取
  3. * @return 返回值
  4. */
  5. $scope.getQueryString = function() {
  6. var url= {},
  7. a = '';
  8. (a = window.location.search.substr(1)) || (a = window.location.hash.split('?')[1])
  9. a.split(/&/g).forEach(function(item) {
  10. url[(item = item.split('='))[0]] = item[1];
  11. })
  12. return url
  13. }

193.过滤器指定字段

  1. function filterArrBySex(data, name) {
  2. if (!name) {
  3. console.log(name)
  4. return data;
  5. } else {
  6. return data.filter(function(ele, index, self) {
  7. if (ele.name.includes(name)) {
  8. return ele
  9. }
  10. })
  11. }
  12. }

194.根据身份证获取出生年月

  1. /**
  2. * 根据身份证获取出生年月
  3. * @param idCard
  4. */
  5. function getBirthdayFromIdCard(idCard) {
  6. var birthday = "";
  7. if (idCard != null && idCard != "") {
  8. if (idCard.length == 15) {
  9. birthday = "19" + idCard.substr(6, 6);
  10. } else if (idCard.length == 18) {
  11. birthday = idCard.substr(6, 8);
  12. }
  13. birthday = birthday.replace(/(.{4})(.{2})/, "$1-$2-");
  14. }
  15. return birthday;
  16. }

195.根据身份证获取年龄

  1. /**
  2. * 根据身份证获取年龄
  3. * @param UUserCard
  4. */
  5. function IdCard(UUserCard) {
  6. //获取年龄
  7. var myDate = new Date();
  8. var month = myDate.getMonth() + 1;
  9. var day = myDate.getDate();
  10. var age = myDate.getFullYear() - UUserCard.substring(6, 10) - 1;
  11. if (UUserCard.substring(10, 12) < month || UUserCard.substring(10, 12) == month && UUserCard.substring(12, 14) <= day) {
  12. age++;
  13. }
  14. return age
  15. }

196.原生js滑块验证

  1. //event.clientX:鼠标点下的点到左侧x轴的距离
  2. window.onload = function() {
  3. //事件处理 onmousedown onmousemove onmouseup
  4. var box = document.querySelector(".box")
  5. var btn = document.querySelector(".btn")
  6. var bg = document.querySelector(".bg")
  7. var text1 = document.querySelector(".text")
  8. //封装的选择器 声明式函数可以提升
  9. // function fun(){
  10. //
  11. // }
  12. var flag = false; //标记
  13. btn.onmousedown = function(event) {
  14. var downx = event.clientX; //按下后获取的与x轴的距离
  15. btn.onmousemove = function(e) {
  16. var movex = e.clientX - downx; //滑块滑动的距离
  17. //移动的范围
  18. if (movex > 0) {
  19. this.style.left = movex + "px";
  20. bg.style.width = movex + "px";
  21. if (movex >= box.offsetWidth - 40) {
  22. //验证成功
  23. flag = true
  24. text1.innerHTML = "验证成功"
  25. text1.style.color = "#fff"
  26. //清除事件
  27. btn.onmousedown = null;
  28. btn.onmousemove = null;
  29. }
  30. }
  31. }
  32. }
  33. //松开事件
  34. btn.onmouseup = function() {
  35. //清除事件
  36. btn.onmousemove = null;
  37. if (flag) return;
  38. this.style.left = 0;
  39. bg.style.width = 0 + "px";
  40. }
  41. }

197.纯 js无限加载瀑布(原创)

  1. //随机[m,n]之间的整数 封装
  2. function randomNumber(m, n) {
  3. return Math.floor(Math.random() * (n - m + 1) + m);
  4. }
  5. //随机颜色 封装
  6. function randomColor() {
  7. return "rgb(" + randomNumber(0, 255) + "," + randomNumber(0, 255) + "," + randomNumber(0, 255) + ")";
  8. }
  9. //获取当前的scrollTop
  10. var scrollTopDistance;
  11. //获取所有的ul
  12. var uls = document.querySelectorAll("ul");
  13. var i = 0;
  14. var k = i;
  15. function waterFall() {
  16. for (i = k; i < k + 4; i++) {
  17. //创建li
  18. var li = document.createElement("li");
  19. //随机颜色
  20. li.style.backgroundColor = randomColor();
  21. //随机高度
  22. li.style.height = randomNumber(120, 400) + "px";
  23. //手动转换为字符串
  24. li.innerHTML = i + 1 + "";
  25. //插入到对应的ul中
  26. //判断哪个ul的高度低,该次创建的li就插入到此ul中
  27. var index = 0; //记录下标
  28. for (var j = 0; j < uls.length; j++) {
  29. if (uls[j].offsetHeight < uls[index].offsetHeight) {
  30. index = j;
  31. }
  32. }
  33. //将元素节点插入文档中
  34. uls[index].appendChild(li);
  35. }
  36. k = i;
  37. return uls[index].offsetHeight;
  38. }
  39. waterFall();
  40. //鼠标滚轮事件,由于右侧没有滚轮,所以使用onmousewheel事件
  41. window.onmousewheel = function() {
  42. //获取窗口的高度,要兼容浏览器
  43. var windowH = document.documentElement.clientHeight;
  44. //滚轮于top的距离,要兼容浏览器
  45. var scrollH = document.documentElement.scrollTop ||
  46. document.body.scrollTop;
  47. //获取窗口的可见高度
  48. var documentH = document.documentElement.scrollHeight ||
  49. document.body.scrollHeight;
  50. //窗口的高度 + 滚轮与顶部的距离 > 窗口的可见高度-200
  51. if (windowH + scrollH > documentH - 200) {
  52. //执行此函数
  53. waterFall()
  54. }
  55. }

198.jQuery两个元素比较高度

  1. $(*function* () {
  2. *var* w_max = 0;
  3. *//求最大高度*
  4. $("#MenuNavigation li").each(*function* () {
  5. *var* w = $(*this*).innerWidth();
  6. w_max = w > w_max ? w : w_max;
  7. })
  8. $("#MenuNavigation li").width(w_max)
  9. *//将最大高度赋值给所有元素,*
  10. })

199.js定时清除缓存,存储缓存,获取缓存

  1. // 封装本地存储的方法
  2. export const storage = {
  3. set: function(variable, value, ttl_ms) {
  4. var data = { value: value, expires_at: new Date(ttl_ms).getTime() };
  5. localStorage.setItem(variable.toString(), JSON.stringify(data));
  6. },
  7. get: function(variable) {
  8. var data = JSON.parse(localStorage.getItem(variable.toString()));
  9. if (data !== null) {
  10. debugger
  11. if (data.expires_at !== null && data.expires_at < new Date().getTime()) {
  12. localStorage.removeItem(variable.toString());
  13. } else {
  14. return data.value;
  15. }
  16. }
  17. return null;
  18. },
  19. remove(key) {
  20. localStorage.removeItem(key);
  21. }
  22. }

200.数组降维

  1. //数组降维
  2. reduceDimension(arr) {
  3. var reduced = [];
  4. for (var i = 0; i < arr.length; i++) {
  5. reduced = reduced.concat(arr[i]);
  6. }
  7. return reduced;
  8. }

201.设置cookie,获取cookie,删除cookie

  1. var cookieUtil = {
  2. getCookie: function (name) {
  3. var arrCookie = document.cookie.split("; ");
  4. for (var i = 0; i < arrCookie.length; i++) {
  5. var cookieItem = arrCookie[i].split('=');
  6. if (cookieItem[0] == name) {
  7. return cookieItem[1];
  8. }
  9. }
  10. return undefined;
  11. },
  12. setCookie: function (name, value, expires, path, domain, secure) {
  13. var cookieText = encodeURIComponent(name) + "=" +
  14. encodeURIComponent(value);
  15. if (expires instanceof Date) {
  16. cookieText += "; expires=" + expires.toGMTString();
  17. }
  18. if (path) {
  19. cookieText += "; path=" + path;
  20. }
  21. if (domain) {
  22. cookieText += "; domain=" + domain;
  23. }
  24. if (secure) {
  25. cookieText += "; secure";
  26. }
  27. document.cookie = cookieText;
  28. },
  29. removeCookie: function (name, path, domain, secure) {
  30. this.set(name, "", new Date(0), path, domain, secure);
  31. }
  32. }

202.判读是否为外链

  1. /**
  2. * @description 判读是否为外链
  3. * @param path
  4. * @returns {boolean}
  5. */
  6. export function isExternal(path) {
  7. return /^(https?:|mailto:|tel:)/.test(path);
  8. }

203.校验密码是否小于6位

  1. /**
  2. * @description 校验密码是否小于6位
  3. * @param str
  4. * @returns {boolean}
  5. */
  6. export function isPassword(str) {
  7. return str.length >= 6;
  8. }

204.判断是否为数字

  1. /**
  2. * @description 判断是否为数字
  3. * @param value
  4. * @returns {boolean}
  5. */
  6. export function isNumber(value) {
  7. const reg = /^[0-9]*$/;
  8. return reg.test(value);
  9. }

205.判断是否为名称

  1. /**
  2. * @description 判断是否是名称
  3. * @param value
  4. * @returns {boolean}
  5. */
  6. export function isName(value) {
  7. const reg = /^[\u4e00-\u9fa5a-zA-Z0-9]+$/;
  8. return reg.test(value);
  9. }

206.判断是否为IP

  1. /**
  2. * @description 判断是否为IP
  3. * @param ip
  4. * @returns {boolean}
  5. */
  6. export function isIP(ip) {
  7. 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])$/;
  8. return reg.test(ip);
  9. }

207.判断是否是传统网站

  1. /**
  2. * @description 判断是否是传统网站
  3. * @param url
  4. * @returns {boolean}
  5. */
  6. export function isUrl(url) {
  7. 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.,?'\\+&%$#=~_-]+))*$/;
  8. return reg.test(url);
  9. }

208.判断是否是小写字母

  1. /**
  2. * @description 判断是否是小写字母
  3. * @param str
  4. * @returns {boolean}
  5. */
  6. export function isLowerCase(str) {
  7. const reg = /^[a-z]+$/;
  8. return reg.test(str);
  9. }

209.判断是否是大写字母

  1. /**
  2. * @description 判断是否是大写字母
  3. * @param str
  4. * @returns {boolean}
  5. */
  6. export function isUpperCase(str) {
  7. const reg = /^[A-Z]+$/;
  8. return reg.test(str);
  9. }

210.判断是否是大写字母开头

  1. /**
  2. * @description 判断是否是大写字母开头
  3. * @param str
  4. * @returns {boolean}
  5. */
  6. export function isAlphabets(str) {
  7. const reg = /^[A-Za-z]+$/;
  8. return reg.test(str);
  9. }

211.判断是否是字符串

  1. /**
  2. * @description 判断是否是字符串
  3. * @param str
  4. * @returns {boolean}
  5. */
  6. export function isString(str) {
  7. return typeof str === "string" || str instanceof String;
  8. }

212.判断是否是数组

  1. /**
  2. * @description 判断是否是数组
  3. * @param arg
  4. * @returns {arg is any[]|boolean}
  5. */
  6. export function isArray(arg) {
  7. if (typeof Array.isArray === "undefined") {
  8. return Object.prototype.toString.call(arg) === "[object Array]";
  9. }
  10. return Array.isArray(arg);
  11. }

213.判断是否是端口号

  1. /**
  2. * @description 判断是否是端口号
  3. * @param str
  4. * @returns {boolean}
  5. */
  6. export function isPort(str) {
  7. 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])$/;
  8. return reg.test(str);
  9. }

214.判断是否是手机号

  1. /**
  2. * @description 判断是否是手机号
  3. * @param str
  4. * @returns {boolean}
  5. */
  6. export function isPhone(str) {
  7. const reg = /^1\d{10}$/;
  8. return reg.test(str);
  9. }

215.判断是否是邮箱

  1. /**
  2. * @description 判断是否是邮箱
  3. * @param str
  4. * @returns {boolean}
  5. */
  6. export function isEmail(str) {
  7. const reg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
  8. return reg.test(str);
  9. }

216.判断是否是中文

  1. /**
  2. * @description 判断是否中文
  3. * @param str
  4. * @returns {boolean}
  5. */
  6. export function isChina(str) {
  7. const reg = /^[\u4E00-\u9FA5]{2,4}$/;
  8. return reg.test(str);
  9. }

217.判断是否为空

  1. /**
  2. * @description 判断是否为空
  3. * @param str
  4. * @returns {boolean}
  5. */
  6. export function isBlank(str) {
  7. return (
  8. str == null ||
  9. false ||
  10. str === "" ||
  11. str.trim() === "" ||
  12. str.toLocaleLowerCase().trim() === "null"
  13. );
  14. }

218.判断是否为固话

  1. /**
  2. * @description 判断是否为固话
  3. * @param str
  4. * @returns {boolean}
  5. */
  6. export function isTel(str) {
  7. const reg = /^(400|800)([0-9\\-]{7,10})|(([0-9]{4}|[0-9]{3})(-| )?)?([0-9]{7,8})((-| |转)*([0-9]{1,4}))?$/;
  8. return reg.test(str);
  9. }

219.判断是否为数字且最多两位小数

  1. /**
  2. * @description 判断是否为数字且最多两位小数
  3. * @param str
  4. * @returns {boolean}
  5. */
  6. export function isNum(str) {
  7. const reg = /^\d+(\.\d{1,2})?$/;
  8. return reg.test(str);
  9. }

220.判断经度 -180.0~+180.0(整数部分为0~180,必须输入1到5位小数)

  1. /**
  2. * @description 判断经度 -180.0~+180.0(整数部分为0~180,必须输入1到5位小数)
  3. * @param str
  4. * @returns {boolean}
  5. */
  6. export function isLongitude(str) {
  7. const reg = /^[-|+]?(0?\d{1,2}\.\d{1,5}|1[0-7]?\d{1}\.\d{1,5}|180\.0{1,5})$/;
  8. return reg.test(str);
  9. }

221.判断纬度 -90.0~+90.0(整数部分为0~90,必须输入1到5位小数)

  1. /**
  2. * @description 判断纬度 -90.0~+90.0(整数部分为0~90,必须输入1到5位小数)
  3. * @param str
  4. * @returns {boolean}
  5. */
  6. export function isLatitude(str) {
  7. const reg = /^[-|+]?([0-8]?\d{1}\.\d{1,5}|90\.0{1,5})$/;
  8. return reg.test(str);
  9. }

222.rtsp校验只要有rtsp://

  1. /**
  2. * @description rtsp校验,只要有rtsp://
  3. * @param str
  4. * @returns {boolean}
  5. */
  6. export function isRTSP(str) {
  7. 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])$/;
  8. 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}/;
  9. 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])\//;
  10. return reg.test(str) || reg1.test(str) || reg2.test(str);
  11. }

223.判断IE浏览器版本和检测是否为非IE浏览器

  1. function IEVersion() {
  2. var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
  3. var isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1; //判断是否IE<11浏览器
  4. var isEdge = userAgent.indexOf("Edge") > -1 && !isIE; //判断是否IE的Edge浏览器
  5. var isIE11 = userAgent.indexOf('Trident') > -1 && userAgent.indexOf("rv:11.0") > -1;
  6. if (isIE) {
  7. var reIE = new RegExp("MSIE (\\d+\\.\\d+);");
  8. reIE.test(userAgent);
  9. var fIEVersion = parseFloat(RegExp["$1"]);
  10. if (fIEVersion == 7) {
  11. return 7;
  12. } else if (fIEVersion == 8) {
  13. return 8;
  14. } else if (fIEVersion == 9) {
  15. return 9;
  16. } else if (fIEVersion == 10) {
  17. return 10;
  18. } else {
  19. return 6; //IE版本<=7
  20. }
  21. } else if (isEdge) {
  22. return 'edge'; //edge
  23. } else if (isIE11) {
  24. return 11; //IE11
  25. } else {
  26. return -1; //不是ie浏览器
  27. }
  28. }

224.数组去重

方案一:Set + …

  1. function noRepeat(arr) {
  2. return [...new Set(arr)];
  3. }
  4. noRepeat([1,2,3,1,2,3])

方案二:Set + Array.from

  1. function noRepeat(arr) {
  2. return Array.from(new Set(arr));
  3. }
  4. noRepeat([1,2,3,1,2,3])

方案三:双重遍历比对下标

  1. function noRepeat(arr) {
  2. return arr.filter((v, idx)=>idx == arr.lastIndexOf(v))
  3. }
  4. noRepeat([1,2,3,1,2,3])

方案四:单遍历 + Object 特性

Object 的特性是 Key 不会重复。
这里使用 values 是因为可以保留类型,keys 会变成字符串。

  1. function noRepeat(arr) {
  2. return Object.values(arr.reduce((s,n)=>{
  3. s[n] = n;
  4. return s
  5. },{}))
  6. }
  7. noRepeat([1,2,3,1,2,3])