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+"日";
    }

實用方法:

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<B return -1
 * A=B return 0
 */
$.compareTime = function(time1,time2) {
    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 -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<length; i++){ 
      if (form.itemId[i].disabled != true){
        form.itemId[i].checked = tocheck;
      }       
    }
  else {
    if (form.itemId.disabled !=true){
      form.itemId.checked = tocheck;
    }
  }
}

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)

//返回最近七天的日期
    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)

//返回最近七天的日期
    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工具函數的資料請關註WalkonNet其它相關文章!

推薦閱讀: