前端常用工具类方法

背景

在日常开发中,我们经常会用一些工具类方法来实现业务逻辑 下面列举几种最常用的

URL截取参数

//直接调用输入想要截取的参数名称几个
export function getParamFromUrl(key) {
    if (key === undefined) return null;
    let search = location.search.substr(1);
    let mReg = new RegExp('(^|&)' + key + '=([^&]*)(&|$)');
    let mValue = search.match(mReg);
    if (mValue != null) return unescape(mValue[2]);
    return null;
}
//示例
let city = getParamFromUrl('city');

JSON是否为空判断

//输入想要检测的json数据 如果为空返回返回false
export function isNullObject(model) {
  if (typeof model === "object") {
    let hasProp = false;
    for (const prop in model) {
        hasProp = true;
        break;
    }
    if (hasProp) {
        return false;
    }
    return true;
  } else {
      throw "model is not object";
  }
}

image-20200929171431032

数据类型检测

//检测变量的数据类型
export function getParamType(item) {
    if (item === null) return null;
    if (item === undefined) return undefined;
    return Object.prototype.toString.call(item).slice(8, -1);
}
//返回String Function Boolean Object Number

image-20200929171150164

获取cookie

//获取document下cookie的具体某个参数值
export function getCookie(key) {
    if (key === undefined) {
        return undefined;
    }
    let cookies = document.cookie;
    let mReg = new RegExp('(^|;)\\s*' + key + '=([^;]*)(;|$)');
    let mValue = cookies.match(mReg);
    let ret = undefined;
    if (mValue != null) {
        ret = unescape(mValue[2]);
    }
    if (ret !== undefined) {
        ret = ret.replace(/^\"|\'/i, '').replace(/\"|\'$/i, '');
    }
    return ret;
}

image-20200930103240035

版本号对比

一般在做APP端开发的时候需要用到一些版本控制,那么就需要针对版本号来进行对比,高版本或者低版本做一些特殊的逻辑处理,下面就是提供版本对比的方法

//传入要对比的版本号,一般前面一个传入当前的版本号,后面一个写上要对比的版本号
export function versionCompare(higher, lower) {
    let sep = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '.';

    let higherAry = higher.split(sep),
        lowerAry = lower.split(sep);
    let l = Math.max(higherAry.length, lowerAry.length);
    for (let i = 0; i < l; i++) {
        let high = parseInt(higherAry[i] || 0);
        let low = parseInt(lowerAry[i] || 0);
        if (high > low) {
            return 1;
        }
        if (high < low) {
            return -1;
        }
    }
    return 0;
}
//返回值  higher > lower: 1;higher = lower: 0;higher < lower:-1

image-20200930103754427

数组去重

export function arrayUniq(array){
    let temp = []; 
    for(let i = 0; i < array.length; i++){
        if(temp.indexOf(array[i]) == -1){
            temp.push(array[i]);
        }
    }
    return temp;
}

image-20200930104914363

iPhone X系列机型判断

export function isIphoneX() {
    // iPhone X、iPhone XS
    let isIPhoneX =
        /iphone/gi.test(window.navigator.userAgent) &&
        window.devicePixelRatio &&
        window.devicePixelRatio === 3 &&
        window.screen.width === 375 &&
        window.screen.height === 812;
    // iPhone XS Max
    let isIPhoneXSMax =
        /iphone/gi.test(window.navigator.userAgent) &&
        window.devicePixelRatio &&
        window.devicePixelRatio === 3 &&
        window.screen.width === 414 &&
        window.screen.height === 896;
    // iPhone XR
    let isIPhoneXR =
        /iphone/gi.test(window.navigator.userAgent) &&
        window.devicePixelRatio &&
        window.devicePixelRatio === 2 &&
        window.screen.width === 414 &&
        window.screen.height === 896;
    if (isIPhoneX || isIPhoneXSMax || isIPhoneXR) {
        return true;
    }
    return false;
}

浏览器内核检测

export function checkBrowser() {
  const u = navigator.userAgent;
  const obj = {
    trident: u.indexOf("Trident") > -1, //IE内核
    presto: u.indexOf("Presto") > -1, //opera内核
    webKit: u.indexOf("AppleWebKit") > -1, //苹果、谷歌内核
    gecko: u.indexOf("Gecko") > -1 && u.indexOf("KHTML") == -1, //火狐内核
  }
  return Object.keys(obj)[Object.values(obj).indexOf(true)];
}

image-20201019102326521

localStorage相关处理

//localStorage取值
export function getLocalStorageItem(key) {
    return localStorage.getItem(key);
}
//localStorage存值
export function setLocalStorageItem(key, value) {
  if (typeof (value) === 'object') value = JSON.stringify(value);
  localStorage.setItem(key, value);
}
//localStorage删除值
export function removeLocalStorageItem(key) {
    return localStorage.removeItem(key);
}

image-20201019104657127

时间格式化

export function getFillDate(key) {
  if(key < 10) {
    return `0${key}`;
  }else{
    return `${key}`;
  }
}
/**
 * 时间戳转化为年月日
 * @param times 时间戳
 * @param ymd 格式类型(yyyy-mm-dd,yyyy/mm/dd)
 * @param hms 可选,格式类型(hh,hh:mm,hh:mm:ss)
 * @returns {年月日}
 */
export function dateFomat (times, ymd,  hms) {
  const oDate = new Date(times)
  const oYear = oDate.getFullYear()
  const oMonth = oDate.getMonth() + 1
  const oDay = oDate.getDate()
  const oHour = oDate.getHours()
  const oMin = oDate.getMinutes()
  const oSec = oDate.getSeconds()
  let oTime // 最后拼接时间
  // 年月日格式
  switch (ymd) {
    case 'yyyy-mm-dd':
      oTime = oYear + '-' + getFillDate(oMonth) + '-' + getFillDate(oDay)
      break
    case 'yyyy/mm/dd':
      oTime = oYear + '/' + getFillDate(oMonth) + '/' + getFillDate(oDay)
      break
  }
  // 时分秒格式
  switch (hms) {
    case 'hh':
      oTime = oTime + ' ' + getFillDate(oHour)
      break
    case 'hh:mm':
      oTime = oTime + ' ' + getFillDate(oHour) + ':' + getFillDate(oMin)
      break
    case 'hh:mm:ss':
      oTime = oTime + ' ' + getFillDate(oHour) + ':' + getFillDate(oMin) + ':' + getFillDate(oSec)
      break
  }
  return oTime
}

image-20201019111954118

JSON转URL参数

export function paramsToUrlQuery(params) {
    let types = Object.prototype.toString.call(params).slice(8, -1);
    if (types === 'Object') {
        let tempArr = [];
        for (let i in params) {
            let key = encodeURIComponent(i);
            let value = encodeURIComponent(params[i]);
            tempArr.push(key + '=' + value);
        }
        let urlParamsStr = tempArr.join('&');
        return urlParamsStr;
    } else {
        throw 'model is not object';
    }
}

image-20201021110205911

删除url指定参数

export function delUrlParam(url, key) {
    let baseUrl = url.split('?')[0] + '?';
    let query = url.split('?')[1];
    if (query.indexOf(key) > -1) {
        let obj = {};
        let arr = query.split('&');
        for (let i = 0; i < arr.length; i++) {
            arr[i] = arr[i].split('=');
            obj[arr[i][0]] = arr[i][1];
        }
        delete obj[key];
        let url =
            baseUrl +
            JSON.stringify(obj)
                .replace(/[\"\{\}]/g, '')
                .replace(/\:/g, '=')
                .replace(/\,/g, '&');
        return url;
    } else {
        return url;
    }
}

image-20201021154629569

获取url全部参数转json

export function getAllUrlParamsToJson (url) {
  let urlRes = url ? url : window.location.href;
  let _pa = urlRes.substring(urlRes.indexOf('?') + 1),
      _arrS = _pa.split('&'),
      _rs = {};
  for (let i = 0, _len = _arrS.length; i < _len; i++) {
      let pos = _arrS[i].indexOf('=');
      if (pos == -1) {
          continue;
      }
      let name = _arrS[i].substring(0, pos),
          value = window.decodeURIComponent(_arrS[i].substring(pos + 1));
      _rs[name] = value;
  }
  return _rs;
}

image-20201021160959984

去除字符串空格

/**
 * @description 去除空格
 * @param { string } str 待处理字符串
 * @param  { number } type 去除空格类型 1-所有空格  2-前后空格  3-前空格 4-后空格 默认为1
 */
export function trim(str, type = 1) {
    if (type && type !== 1 && type !== 2 && type !== 3 && type !== 4) return;
    switch (type) {
        case 1:
            return str.replace(/\s/g, '');
        case 2:
            return str.replace(/(^\s)|(\s*$)/g, '');
        case 3:
            return str.replace(/(^\s)/g, '');
        case 4:
            return str.replace(/(\s$)/g, '');
        default:
            return str;
    }
}

image-20201021140442396


   转载规则


《前端常用工具类方法》 浅夏晴空 采用 知识共享署名 4.0 国际许可协议 进行许可。
 上一篇
JQuery源码解析 JQuery源码解析
github 上关于 jQuery 源码的全文注解,感兴趣的可以围观一下。jQuery v1.10.2 源码注解(https://github.com/chokcoco/jQuery-) 。 整体架构 不同于 jQuery 代码各个模块细节
2020-11-03
下一篇 
React+TS弹窗 React+TS弹窗
背景在日常的需求开发中我们经常需要用到弹窗,那么在我们构建弹窗时,在引用组件是都需要引入组件DOM,然后通过事件来控制组件的影藏显示,调用也不是很方便; 本组件使用事前注册DOM的方式,业务方在使用时刻直接调用暴露的方法即可,无需再引用DO
2020-09-29
  目录