35个JS中实用工具函数的代码分享

1.Js天数相加获取新日期

function timestampToTime(timestamp) {
        var date = new Date(timestamp);//时间戳为10位需*1000,时间戳为13位的话不需乘1000
        var Y = date.getFullYear();
        var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1):date.getMonth()+1);
        var D = (date.getDate()< 10 ? '0'+date.getDate():date.getDate());
        return Y+"年"+M+"月"+D+"日";
    }

实用方法:

35个JS中实用工具函数的代码分享_第1张图片

2.获取当前日期(yyyyMMdd格式)

function getNowFormatDate() {
        var date = new Date();
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        var currentdate = year + "年" + month + "月" + strDate + "日";
        $("#time").html(currentdate)
        return currentdate;
    }

3.四舍五入

function toDecimal(x) {
        var f = parseFloat(x);
        if (isNaN(f)) {
            return;
        }
        f = Math.round(x*100)/100;
        return f;
    }

4.Js将数字转成中文大写数字

var digitUppercase = function(n) {
        var fraction = ['角', '分'];
        var digit = [
            '零', '壹', '贰', '叁', '肆',
            '伍', '陆', '柒', '捌', '玖'
        ];
        var unit = [
            ['元', '万', '亿'],
            ['', '拾', '佰', '仟']
        ];
        var head = n < 0 ? '欠' : '';
        n = Math.abs(n);
        var s = '';
        for (var 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 (var i = 0; i < unit[0].length && n > 0; i++) {
            var p = '';
            for (var 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 head + s.replace(/(零.)*零元/, '元')
                .replace(/(零.)+/g, '零')
                .replace(/^整$/, '零元整');
    }

5.判断数据是否为空

function dataIsNotNull(data) {
        if (data != null && typeof(data) != "undefined" && data != "" && data != "''" && data != '') {
            return true;
        }
        else {
            return false;
        }
    }

6.字符串日期比较

/* 比较俩个字符串时间A-B
 * A>B return 1
 * A new Date(time2.replace("-", "/").replace("-", "/")).getTime()) {
        return 1;
    }else if(new Date(time1.replace("-", "/").replace("-", "/")).getTime() < new Date(time2.replace("-", "/").replace("-", "/")).getTime()) {
        return -1;
    }else if(new Date(time1.replace("-", "/").replace("-", "/")).getTime() == new Date(time2.replace("-", "/").replace("-", "/")).getTime()) {
        return 0;
    }else {
        return 2;
    }
};

7.验证邮件

function verifyEmailAddress(strEmail){
  var myReg = /^[_a-zA-Z0-9_-_._-]+@([_a-zA-Z0-9_-]+\.)+[a-zA-Z]{2,3}$/;
  return myReg.test(strEmail);
}

8.判断是否为日期数据

function itIsDate(DateString , Dilimeter) 
{ 
  if (DateString==null) return false; 
  if (Dilimeter=='' || Dilimeter==null) 
   Dilimeter = '-'; 
  var tempy=''; 
  var tempm=''; 
  var tempd=''; 
  var tempArray; 
  if (DateString.length<8 && DateString.length>10) 
    return false;    
  tempArray = DateString.split(Dilimeter); 
  if (tempArray.length!=3) 
   return false; 
  if (tempArray[0].length==4) 
  { 
   tempy = tempArray[0]; 
   tempd = tempArray[2]; 
  } 
  else 
  { 
   tempy = tempArray[2]; 
   tempd = tempArray[1]; 
  } 
  tempm = tempArray[1]; 
  var tDateString = tempy + '/'+tempm + '/'+tempd+' 8:0:0';//加八小时是因为我们处于东八区 
  var tempDate = new Date(tDateString); 
  if (isNaN(tempDate)) 
   return false; 
 if (((tempDate.getUTCFullYear()).toString()==tempy) && (tempDate.getMonth()==parseInt(tempm)-1) && (tempDate.getDate()==parseInt(tempd))) 
  { 
   return true; 
  } 
  else 
  { 
   return false; 
  } 
}

9.复选框的全选与取消

function CheckAll(form){
  var length = form.itemId.length;
  var tocheck = form.chkall.checked;
  if (length)
    for (var i=0; i 
 

10.数字输入控制

function InputIntNumberCheck(){
  //为支持IE 或 Netscape
  var theEvent=window.event || arguments.callee.caller.arguments[0]; 
  var elm ;
  var ver = navigator.appVersion;
  if (ver.indexOf("MSIE") != -1){  // IE
    if ( !((theEvent.keyCode >=48)&&(theEvent.keyCode<=57))){
      theEvent.keyCode=0;
    }
  }else{ // Netscape
    if ( !((theEvent.which >=48)&&(theEvent.which<=57))){
      theEvent.stopPropagation();
      theEvent.preventDefault();
    }
  }
  //
}

11.设置以及获取cookie

function setCookie(name, value, Hours) {
    var d = new Date();
    var offset = 8;
    var utc = d.getTime() + (d.getTimezoneOffset() * 60000);
    var nd = utc + (3600000 * offset);
    var exp = new Date(nd);
    exp.setTime(exp.getTime() + Hours * 60 * 60 * 1000);
    document.cookie = name + "=" + escape(value) + ";path=/;expires=" + exp.toGMTString() + ";domain=360doc.com;"
}
function getCookie(name) {
    var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
    if (arr != null) return unescape(arr[2]);
    return null
}

12.数据排序

function sort(arr, type = 1) {
    return arr.sort((a, b) => {
        switch (type) {
            case 1:
                return a - b;
            case 2:
                return b - a;
            case 3:
                return Math.random() - 0.5;
            default:
                return arr;
        }
    })
}

13.记忆函数(缓存函数运算结果)

function cached(fn) {
  let cache = Object.create(null);
  return function cachedFn(str) {
    let hit = cache[str];
    return hit || (cache[str] = fn(str))
  }
}

14.获取浏览器信息

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

15.数组去重 返回一个新数组

function unique(arr){
  if(!isArrayLink(arr)){ //不是类数组对象
    return arr
  }
  let result = []
  let objarr = []
  let obj = Object.create(null)
   
  arr.forEach(item => {
    if(isStatic(item)){//是除了symbol外的原始数据
      let key = item + '_' + getRawType(item);
      if(!obj[key]){
        obj[key] = true
        result.push(item)
      }
    }else{//引用类型及symbol
      if(!objarr.includes(item)){
        objarr.push(item)
        result.push(item)
      }
    }
  })
   
  return resulte
}

16.Base64数据导出文件 文件下载

function downloadFile(filename, data){
  let DownloadLink = document.createElement('a');
 
  if ( DownloadLink ){
    document.body.appendChild(DownloadLink);
    DownloadLink.style = 'display: none';
    DownloadLink.download = filename;
    DownloadLink.href = data;
 
    if ( document.createEvent ){
      let DownloadEvt = document.createEvent('MouseEvents');
 
      DownloadEvt.initEvent('click', true, false);
      DownloadLink.dispatchEvent(DownloadEvt);
    }
    else if ( document.createEventObject )
      DownloadLink.fireEvent('onclick');
    else if (typeof DownloadLink.onclick == 'function' )
      DownloadLink.onclick();
 
    document.body.removeChild(DownloadLink);
  }
}

17.全屏

function toFullScreen(){
  let elem = document.body;
  elem.webkitRequestFullScreen 
  ? elem.webkitRequestFullScreen()
  : elem.mozRequestFullScreen
  ? elem.mozRequestFullScreen()
  : elem.msRequestFullscreen
  ? elem.msRequestFullscreen()
  : elem.requestFullScreen
  ? elem.requestFullScreen()
  : alert("浏览器不支持全屏");
}

18.退出全屏

function toFullScreen(){
  let elem = document.body;
  elem.webkitRequestFullScreen 
  ? elem.webkitRequestFullScreen()
  : elem.mozRequestFullScreen
  ? elem.mozRequestFullScreen()
  : elem.msRequestFullscreen
  ? elem.msRequestFullscreen()
  : elem.requestFullScreen
  ? elem.requestFullScreen()
  : alert("浏览器不支持全屏");
}

19.求出数组中最大非NaN值

function max(arr){
  arr = arr.filter(item => !_isNaN(item))
  return arr.length ? Math.max.apply(null, arr) : undefined
}
//max([1, 2, '11', null, 'fdf', []]) ==> 11

20.求出数组中最小非NaN值

function min(arr){
  arr = arr.filter(item => !_isNaN(item))
  return arr.length ? Math.min.apply(null, arr) : undefined
}
//min([1, 2, '11', null, 'fdf', []]) ==> 1

21.使用正则验证数字

function isNumber(val){
    var regPos = /^\d+(\.\d+)?$/; //非负浮点数
    var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
    if(regPos.test(val) || regNeg.test(val)){
        return true;
    }else{
        return false;
    }
}

22.验证数组是否有重复元素

function hasRepeatValue(a) {
        return /(\x0f[^\x0f]+)\x0f[\s\S]*\1/.test("\x0f" + a.join("\x0f\x0f") + "\x0f");
}

23.提取身份证中性别及出生日期信息

身份证号 倒数第二位是性别,奇数为男,偶数为女

function getIdcardData(){
   var ido=document.getElementById('idCardNumberHandle');//身份证号input元素的ID
   var bd=document.getElementById('birthdayHandle');
   var sex=document.getElementById('sexHandle');
   if(!/^\d{6}((?:19|20)((?:\d{2}(?:0[13578]|1[02])(?:0[1-9]|[12]\d|3[01]))|(?:\d{2}(?:0[13456789]|1[012])(?:0[1-9]|[12]\d|30))|(?:\d{2}02(?:0[1-9]|1\d|2[0-8]))|(?:(?:0[48]|[2468][048]|[13579][26])0229)))\d{2}(\d)[xX\d]$/.test(ido.value)){
      alert('身份证号非法.');
      return;
   }
   bd.value=(RegExp.$1).substr(0,4)+'-'+(RegExp.$1).substr(4,2)+'-'+(RegExp.$1).substr(6,2);//设置出生日期
   ex.value=(parseInt(ido.value.charAt(ido.value.length-2))%2==0?'女':'男');//设置性别
}

24.在现有元素后插入一个新元素

function insertAfter(newElement,targetElement){
  var parent = targetElement.parentNode;
  if (parent.lastChild == targetElement) {
    parent.appendChild(newElement);
  } else {
    parent.insertBefore(newElement,targetElement.nextSubling)
  }
}

25.获取浏览器url中的参数值

var getURLParam = function(name) {
    return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)', "ig").exec(location.search) || [, ""])[1].replace(/\+/g, '%20')) || null;
};

26.深度拷贝对象

function cloneObj(obj) {
    var o = obj.constructor == Object ? new obj.constructor() : new obj.constructor(obj.valueOf());
    for(var key in obj){
        if(o[key] != obj[key] ){
            if(typeof(obj[key]) == 'object' ){
                o[key] = mods.cloneObj(obj[key]);
            }else{
                o[key] = obj[key];
            }
        }
    }
    return o;
}

27.生成随机数

function randombetween(min, max){
    return min + (Math.random() * (max-min +1));
}

28.判断是手机还是pc端

function browserRedirect() {
                var sUserAgent = navigator.userAgent.toLowerCase();
                var bIsIpad = sUserAgent.match(/ipad/i) == "ipad";
                var bIsIphoneOs = sUserAgent.match(/iphone os/i) == "iphone os";
                var bIsMidp = sUserAgent.match(/midp/i) == "midp";
                var bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4";
                var bIsUc = sUserAgent.match(/ucweb/i) == "ucweb";
                var bIsAndroid = sUserAgent.match(/android/i) == "android";
                var bIsCE = sUserAgent.match(/windows ce/i) == "windows ce";
                var bIsWM = sUserAgent.match(/windows mobile/i) == "windows mobile";
                if (bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM) {               
                    //手机端
                } else {        
                    //pc端
                    $('*').css("width",'100%');  
                    $('*').css("height",'100%');  
                }
            }
            browserRedirect();      //判断是手机端还是pc端
            $(function(){
                var h = window.screen.height;
                var w = window.screen.width;
                $('#myiframe').attr("width",w);  //把宽属性追加进去
                $('#myiframe').attr("height",h);  //把高属性追加进去
            })

29.根据出生日期计算年龄

//计算年龄
    function getAge(strBirthday) {
        var a = /^(\d{4})-(\d{2})-(\d{2})$/
        if (a.test(strBirthday)) {
            var birthYear = strBirthday.substring(0, 4);
            var year = new Date();
            var Nyear = year.getFullYear();
            var Nage = Nyear - birthYear;
            if (Nage <= 0) {
                Nage = 1;
            }
            return Nage;//返回年龄
        } else {
            return "";
        }
    }

30.BMI计算

//BMI计算
    function getBMI(w, h) {
        h = h * 0.01;
        var bmi = (w / (h * h)).toFixed(4);
        return bmi;
    }

31.体表面积计算

//体表面积计算
    function getBodyArea(w, h) {
        var bodyArea = (0.0061 * h + 0.0128 * w - 0.1529).toFixed(4);
        return bodyArea;
    }

32.根据身份证获取出生日期以及年龄

//根据身份证获取出生日期以及相应年龄是多少
                        $("#idNumber").on("blur", function () {
                            var num = Number($("#idNumber").val().split("").slice(6, 10).join(""))
                            var mon = $("#idNumber").val().substring(10, 12)
                            var da = $("#idNumber").val().substring(12, 14)
                            var birth = num + "/" + mon + "/" + da
                            var dt = new Date()
                            var year = dt.getFullYear()
                            $("#birthday").val(birth)
                            $("#age").text(year - num)
                        })

33.判断字符串是否是数字

function isNumber(val) {
        var regPos = /^\d+(\.\d+)?$/;//非负浮点数
        var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/;//负浮点数
        if(regPos.test(val) || regNeg.test(val)) {
            return true;
        }else {
            return false;
        }
    }

34.查询最近七天的日期(前七天 当前日期2021-10-13)

35个JS中实用工具函数的代码分享_第2张图片

//返回最近七天的日期
    function getday2() {
        var days = [];
        var date = new Date();
        for(var i=0; i<=144;i+=24){    //144是前六天的小时数
            var dateItem=new Date(date.getTime() - i * 60 * 60 * 1000);  //使用当天时间戳减去以前的时间毫秒(小时*分*秒*毫秒)
            var y = dateItem.getFullYear();  //获取年份
            var m = dateItem.getMonth() + 1;  //获取月份js月份从0开始,需要+1
            var d= dateItem.getDate();  //获取日期
            m = addDate0(m);  //给为单数的月份补零
            d = addDate0(d);  //给为单数的日期补零
            var valueItem= y + '-' + m + '-' + d;  //组合
            days.push(valueItem);  //添加至数组
        }
        console.log('最近七天日期:',days);

        return days;
    }

    //给日期加0
    function addDate0(time) {
        if (time.toString().length == 1) {
            time = '0' + time.toString();
        }
        return time;
    }

35.查询最近七天的日期(后七天 当前日期2021-10-13)

35个JS中实用工具函数的代码分享_第3张图片

//返回最近七天的日期
    function getday2() {
        var days = [];
        var date = new Date();
        for(var i=0; i<=144;i+=24){    //144是前六天的小时数
            var dateItem=new Date(date.getTime() + i * 60 * 60 * 1000);  //使用当天时间戳减去以前的时间毫秒(小时*分*秒*毫秒)
            var y = dateItem.getFullYear();  //获取年份
            var m = dateItem.getMonth() + 1;  //获取月份js月份从0开始,需要+1
            var d= dateItem.getDate();  //获取日期
            m = addDate0(m);  //给为单数的月份补零
            d = addDate0(d);  //给为单数的日期补零
            var valueItem= y + '-' + m + '-' + d;  //组合
            days.push(valueItem);  //添加至数组
        }
        console.log('最近七天日期:',days);

        return days;
    }

    //给日期加0
    function addDate0(time) {
        if (time.toString().length == 1) {
            time = '0' + time.toString();
        }
        return time;
    }

以上就是35个JS中实用工具函数的代码分享的详细内容,更多关于JS工具函数的资料请关注脚本之家其它相关文章!

你可能感兴趣的:(35个JS中实用工具函数的代码分享)