首页 > 其他分享 >值得收藏的前端开发必备工具类函数

值得收藏的前端开发必备工具类函数

时间:2023-08-29 14:59:50浏览次数:32  
标签:const 必备 value 收藏 export let return 前端开发 metric

 

/**
 * 空值: [undefined, null, NaN, [], {}], 注意非空:0, false;
 * @param {*} value 
 * @returns Boolean
 */
function isEmpty(value) {
    switch (Object.prototype.toString.call(value)) {
      case '[object Undefined]':
        return value === void 0;
      case '[object Null]':
        return value === null;
      case '[object Number]':
        return isNaN(value);
      case '[object String]':
        return value === "";
      case '[object Boolean]':
        return false;
      case '[object Object]':
        return Object.keys(value).length === 0;
      case '[object Array]':
        return value.length === 0;
      default:
        return false;
    }
  }
  /**
  * el是否包含某个class
  */
  export const hasClass = (el, className) => {    let reg = new RegExp('(^|\\s)' + className + '(\\s|$)')    return reg.test(el.className)}
  
  /**
  *el添加某个class
  */
  export const addClass = (el, className) => {    if (hasClass(el, className)) {        return    }    let newClass = el.className.split(' ')    newClass.push(className)    el.className = newClass.join(' ')}
  
  /**
  * el去除某个class
  */
  export const removeClass = (el, className) => {    if (!hasClass(el, className)) {        return    }    let reg = new RegExp('(^|\\s)' + className + '(\\s|$)', 'g')    el.className = el.className.replace(reg, ' ')}
  
  
  /**
  *去除html标签
  */
  
  export const removeHtmltag = (str) => {
      return str.replace(/<[^>]+>/g, '')
  }
  
  /**
   * 判断当前环境是否是手机端
   * 
   * @return {Boolean}  返回结果
   * 
   */
   export const isMobile=() =>{
       if(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
              return true
          } else {
              return false
        }
     }
     
        
  /**
   * 断当前环境是否是微信环境
   * 
   * @return {Boolean}  返回结果
   * 
   */
  export const isWeixin =() =>{      
        const ua = navigator.userAgent.toLowerCase();
        if(ua.match(/MicroMessenger/i)==="micromessenger") {
             return true;
       } else {
              return false;
        }
    }
  
  
  /**
   * 检测浏览器是否放大
   * 
   * @param {Boolean } rsize  是否返回具体放大数值,默认否
   * @return {Boolean | Number}  返回结果
   * 
   */
  export const detectZoom=rsize =>{
    let ratio = 0
    const screen = window.screen
    const ua = navigator.userAgent.toLowerCase()
  
    if (window.devicePixelRatio) {
      ratio = window.devicePixelRatio
    } else if (~ua.indexOf('msie')) {
      if (screen.deviceXDPI && screen.logicalXDPI) ratio = screen.deviceXDPI / screen.logicalXDPI
    } else if (window.outerWidth&& window.innerWidth) {
      ratio = window.outerWidth / window.innerWidth
    }
  
    if (ratio) ratio = Math.round(ratio * 100)
  
    return rsize ? ratio : ratio === 100
  }
  
  /**
   * 获取普通地址url参数
   * 例如:http://localhost:8080/?token=rTyJ7bcRb7KU4DMcWo4216&roleId=512213631174180864
   * 
   * @param {String} name 
   * @return {Boolean | String} 返回获取值 
   * 
   */
  export const getUrlParam = name =>{
    const reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); 
    const r = window.location.search.substr(1).match(reg);  
    if (r != null) return decodeURI(r[2]); return false; 
  }
  
  
  /**
   * 获取hash模式地址url参数
   * 例如:http://localhost:8080/#/?token=rTyJ7bcRb7KU4DMcWo4216&roleId=512213631174180864
   * 
   * @param {String} name 
   * @return {Boolean | String} 返回获取值 
   * 
   */
  export const getUrlHashParam =name =>{
    const w = window.location.hash.indexOf("?");
    const query = window.location.hash.substring(w + 1);
    const vars = query.split("&");
    for (let i = 0; i < vars.length; i++) {
      const pair = vars[i].split("=");
      if (pair[0] == name) {
        return pair[1];
      }
    }
  
    return false;
  }
  
  /**
   * 时间戳转换
   * 
   * @param {Number} date 时间戳
   * @param {String} fmt  时间显示格式,例如 yyyy-MM-dd HH:mm:ss
   * @return {String} fmt 返回转换后的时间 ,formatDate(value, "yyyy-MM-dd  hh: mm : ss")
   * 
   */
  export const formatDate = (date, fmt) => {
    date = new Date(date);
    if (isNaN(date.getDate())) return date;
    if (/(y+)/.test(fmt)) {
      fmt = fmt.replace(
        RegExp.$1,
        (date.getFullYear() + "").substr(4 - RegExp.$1.length)
      );
    }
    let o = {
      "M+": date.getMonth() + 1,
      "d+": date.getDate(),
      "h+": date.getHours(),
      "m+": date.getMinutes(),
      "s+": date.getSeconds()
    };
    for (let k in o) {
      if (new RegExp(`(${k})`).test(fmt)) {
        let str = o[k] + "";
        fmt = fmt.replace(
          RegExp.$1,
          RegExp.$1.length === 1 ? str : ("00" + str).substr(str.length)
        );
      }
    }
    return fmt;
  };
  
  /**
   * 时间戳转换成什么之前
   * 
   * @param {Number} times 时间戳
   * @return {String} 返回结果,timeAgoLabel(1606273724459) 输出:刚刚
   * 
   */
  export const timeAgoLabel = times => {
    let nowTimes = new Date().getTime()
    let diffSecond = (nowTimes - times) / 1000
    let agoLabel = ''
    if (diffSecond < 60) {
      agoLabel = '刚刚'
    } else if (diffSecond < 60 * 60) {
      agoLabel = Math.floor(diffSecond / 60) + '分钟前'
    } else if (diffSecond < 60 * 60 * 24) {
      agoLabel = Math.floor(diffSecond / 3600) + '小时前'
    } else if (diffSecond < 60 * 60 * 24 * 30) {
      agoLabel = Math.floor(diffSecond / (3600 * 24)) + '天前'
    } else if (diffSecond < 3600 * 24 * 30 * 12) {
      agoLabel = Math.floor(diffSecond / (3600 * 24 * 30)) + '月前'
    } else {
      agoLabel = Math.floor(diffSecond / (3600 * 24 * 30 * 12)) + '年前'
    }
    return agoLabel
  }
  
  
  /**
   * 生成任意位数随机数(数字)
   * 
   * @param {Number} n 可选长度位数
   * @return {Number} 返回随机值
   * 
   */
  export const randomNumber =n =>{
        let rnd = '';
        for (let i = 0; i < n; i++) {
          rnd += Math.floor(Math.random() * 10);
        }
        return rnd;
  }
  /**
   * 随机生成一个自定义长度,不重复的字母加数字组合,可用来做id标识
   * 
   * @param {Number} randomLength 可选长度位数,默认10
   * @return {String} 返回随机值
   * 
   */
  export const randomId =(randomLength = 10) =>{
      return Number(Math.random().toString().substr(3,randomLength) + Date.now()).toString(36)
  }
  
   /** 
   * 文件大小换算成单位
   * 
   * @param {Number} bytes 大小
   * @param {String} units 可选单位,默认metric
   * @param {Number} precision 可选位数,数值精度保留几位小数点,默认1
   * @return {String} 返回带单位值,byteSize(1580),输出1.6 kB
   * 
  */
  export const byteSize = (bytes, units='metric', precision=1) => {
      let value='',
          unit=''
      const base = units === 'metric' || units === 'metric_octet' ? 1000 : 1024
      const table = [
          { expFrom: 0, expTo: 1, metric: 'B', iec: 'B', metric_octet: 'o', iec_octet: 'o' },
          { expFrom: 1, expTo: 2, metric: 'kB', iec: 'KiB', metric_octet: 'ko', iec_octet: 'Kio' },
          { expFrom: 2, expTo: 3, metric: 'MB', iec: 'MiB', metric_octet: 'Mo', iec_octet: 'Mio' },
          { expFrom: 3, expTo: 4, metric: 'GB', iec: 'GiB', metric_octet: 'Go', iec_octet: 'Gio' },
          { expFrom: 4, expTo: 5, metric: 'TB', iec: 'TiB', metric_octet: 'To', iec_octet: 'Tio' },
          { expFrom: 5, expTo: 6, metric: 'PB', iec: 'PiB', metric_octet: 'Po', iec_octet: 'Pio' },
          { expFrom: 6, expTo: 7, metric: 'EB', iec: 'EiB', metric_octet: 'Eo', iec_octet: 'Eio' },
          { expFrom: 7, expTo: 8, metric: 'ZB', iec: 'ZiB', metric_octet: 'Zo', iec_octet: 'Zio' },
          { expFrom: 8, expTo: 9, metric: 'YB', iec: 'YiB', metric_octet: 'Yo', iec_octet: 'Yio' }
      ]
  
      for (let i = 0; i < table.length; i++) {
          const lower = Math.pow(base, table[i].expFrom)
          const upper = Math.pow(base, table[i].expTo)
          if (bytes >= lower && bytes < upper) {
              const retUnit = table[i][units]
              if (i === 0) {
                  value = String(bytes)
                  unit = retUnit
                  break;
              } else {
                  value = (bytes / lower).toFixed(precision)
                  unit = retUnit
                  break;
              }
          }
      }
      return `${value} ${unit}`.trim()  
  }
  
  /**
   * 平滑滚动到页面顶部
   * 
   */
  export const scrollToTop = () => {  
      const c = document.documentElement.scrollTop || document.body.scrollTop;  
      if (c > 0) {  
      window.requestAnimationFrame(scrollToTop);  
      window.scrollTo(0, c - c / 8);  
      }  
  }
  
   /**
  * 滚动到页面底部
  */
  export const scrollToBottom = () => {
    window.scrollTo(0, document.documentElement.clientHeight);  
  }
  /**
  *获取可视窗口高度
  */
  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;
  }
  
  
  /**
  *数字千分位分隔
  */
  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; 
          }
      }
  }
  
  /**
  * 全角转换为半角
  */
  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;
  }
  
  /**
  * 半角转换为全角
  */
  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;
  }
  
  
  /**
  * 数字转化为大写金额
  */
  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(/^整$/, '零元整');
  };
  
  /**
  * 数字转化为中文数字
  */
  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]]
        }
      }
     });
  }
  
  /**
  * 存储loalStorage
  */
  export const loalStorageSet = (key, value) => {
      if (!key) return;
      if (typeof value !== 'string') {
          value = JSON.stringify(value);
      }
      window.localStorage.setItem(key, value);
  };
  export const loalStorageGet = (key) => {
      if (!key) return;
      return window.localStorage.getItem(key);
  };
  export const loalStorageRemove = (key) => {
      if (!key) return;
      window.localStorage.removeItem(key);
  };
  export const sessionStorageSet = (key, value) => {
     if (!key) return;
      if (typeof value !== 'string') {
        value = JSON.stringify(value);
      }
      window.sessionStorage.setItem(key, value)
  };
  export const sessionStorageGet = (key) => {
     if (!key) return;
      return window.sessionStorage.getItem(key)
  };
  export const sessionStorageRemove = (key) => {
     if (!key) return;
      window.sessionStorage.removeItem(key)
  };
  

 

标签:const,必备,value,收藏,export,let,return,前端开发,metric
From: https://www.cnblogs.com/yeminglong/p/17664728.html

相关文章

  • 一文搞清楚 iptables 这文太好了不得不收藏
    iptables简介netfilter/iptables(简称为iptables)组成Linux平台下的包过滤防火墙,与大多数的Linux软件一样,这个包过滤防火墙是免费的,它可以代替昂贵的商业防火墙解决方案,完成封包过滤、封包重定向和网络地址转换(NAT)等功能。iptables基础规则(rules)其实就是网络管理员预定义的条件......
  • Linux必备的5款神仙国产软件,让你工作效率成倍提升
    随着近些年来国产化计算机的普及,国内的Linux用户逐渐开始多了起来,虽然Linux操作系统的生态不像Windows那么完善,有众多办公软件可以选择,但也有一定数量的软件资源,其中也包括一些优秀的国产软件。下面我将为大家分享几款Linux必备的神仙国产软件,让你工作效率成倍提升。在线协作文档—......
  • Linux必备的5款神仙国产软件,让你工作效率成倍提升
    随着近些年来国产化计算机的普及,国内的Linux用户逐渐开始多了起来,虽然Linux操作系统的生态不像Windows那么完善,有众多办公软件可以选择,但也有一定数量的软件资源,其中也包括一些优秀的国产软件。下面我将为大家分享几款Linux必备的神仙国产软件,让你工作效率成倍提升。 在线协作......
  • 全栈必备Linux 基础
    Linux 几乎无处不在,不论是服务器构建,还是客户端开发,操作系统的基础技能对全栈来说都是必备的。系统的选择Linux发行版本可以大体分为两类,一类是商业公司维护的发行版本,一类是社区组织维护的发行版本,前者以著名的Redhat(RHEL)为代表,后者以Debian为代表。Redhat,应该称为Re......
  • wap 开发的必备知识 wml语言
    WAP是一种用于在无线终端进行信息服务的主要的标准。WML指无线标记语言。它是一种从HTML继承而来的标记语言,但是WML基于XML,因此它较HTML更严格。WML被用来创建可显示在WAP浏览器中的页面。用WML编写的页面被称为DECKS。DECKS是作为一套CARDS被构造的。主要标签Deck......
  • 京东上货软件必备API(商品主图价格详情批量下载上传)
    一、引言在数字化快速发展的今天,电商平台的商品信息管理变得尤为重要。本文将重点介绍京东上货软件必备的API接口,帮助你实现商品主图、价格、详情的批量下载与上传,提高商品管理效率,优化用户体验。二、京东上货软件必备API  测试地址入口1、商品主图批量下载API通过此API接口,......
  • Java8 新特性全面介绍,强烈建议收藏
    阅读大约10分钟,实用性非常高,建议收藏PC阅读移步文末前言Java8已经公布有一段时间了,种种迹象表明Java8是一个有重大改变的发行版。在JavaCodeGeeks上已经有很多介绍Java8新特性的文章,例如PlayingwithJava8–LambdasandConcurrency、Java8DateTimeAPITu......
  • 怎么使用Kafka?收藏这篇短文就可以了
    〇、前言便于大家对本章内容的理解,我重新整理了一下Kafka中的部分重要概念,以表格的方式呈现出来,请见下表所示:名词解释Broker节点一个Kafka节点就是一个Broker,一个和多个Broker可以组成一个Kafka集群Topic主题Kafka根据topic对消息进行归类,发布到kafka集群的每套......
  • c# .NET 高级编程 高并发必备技巧 - 锁
    锁最为常见的应用就是高并发的情况下,库存的控制。本次只做简单的单机锁介绍。直接看代码:每请求一次库存-1.假如库存1000,在1000个人请求之后,库存将变为0。publicintReduce0(){intr=0;stringkey="stock";stringstoc......
  • 错过这5大AI绘画提示词平台,你会拍大腿!别问,直接收藏!
    如今,AI绘画已经不再是简单的技术展示,而是逐渐转向了商业化的运营。有的人利用AI生成的图片,再结合ChatGPT产生的文字,然后在平台上发布,这样就可以赚取平台的广告费。其他一些变现操作参考之前的文章:AI飞行家:AI头像壁纸号项目全流程深度拆解AI壁纸号一周增加上千粉丝,轻松变现的......