日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

常用的utlis封裝

作者:農夫三拳有點疼=-= 更新時間: 2023-10-17 編程語言
export function checkMobile(str) {
  const mobileReg = /^1[3456789]\d{9}$/;
  console.log(str);
  console.log(mobileReg.test(str));
  if (mobileReg.test(str)) {
    return true;
  }
  return false;
}

export function checkID(str) {
  const IDReg = /^[1-9]\d{5}(18|19|20|(3\d))\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
  if (IDReg.test(str)) {
    return true;
  }
  return false;
}

export function getAge(birthYear, birthMonth, birthDay) {
  // 定義返回值
  console.log(birthYear);
  let returnAge;
  // 獲取當前時間
  const d = new Date();
  const nowYear = d.getFullYear();
  const nowMonth = d.getMonth() + 1;
  const nowDay = d.getDate();

  // 計算周歲年齡差
  if (nowYear === birthYear) {
    returnAge = 0; // 同年 則為0歲
  } else {
    const ageDiff = nowYear - birthYear; // 年之差
    if (ageDiff > 0) {
      if (nowMonth === birthMonth) {
        const dayDiff = nowDay - birthDay; // 日之差
        if (dayDiff < 0) {
          returnAge = ageDiff - 1;
        } else {
          returnAge = ageDiff;
        }
      } else {
        const monthDiff = nowMonth - birthMonth; // 月之差
        if (monthDiff < 0) {
          returnAge = ageDiff - 1;
        } else {
          returnAge = ageDiff;
        }
      }
    } else {
      returnAge = -1; // 輸入有誤
    }
  }
  console.log(returnAge);
  return returnAge; // 結果彈窗顯示
}

// 千分位
export function numToSplit(value) {
  if (!value || +value === 0) {
    return '0.00';
  }
  let newNum = +value;
  let symbol;
  if (newNum < 0) {
    symbol = 'negative';
    newNum = Math.abs(newNum);
  } else {
    symbol = 'positive';
  }
  if (typeof newNum === 'number') {
    const arr = newNum.toFixed(2).split('.');
    const floatNumber = arr[1];
    const intNumber = arr[0];
    let splitValue = '';
    for (let i = intNumber.length - 1; i >= 0; i -= 1) {
      if ((intNumber.length - 1 - i) % 3 === 0 && i !== intNumber.length - 1) {
        splitValue = `${intNumber[i]},${splitValue}`;
      } else {
        splitValue = intNumber[i] + splitValue;
      }
    }
    if (!splitValue) {
      splitValue = 0;
    }
    return symbol === 'positive' ? `${splitValue}.${floatNumber}` : `-${splitValue}.${floatNumber}`;
  }
  return symbol === 'positive' ? value : `-${value}`;
}

// 數字補0
export function addZero(num) {
  const num2 = parseInt(num, 0);
  if (num2 < 10) {
    return `0${num2}`;
  }
  return num2.toString();
}

// json數組扁平化
export function flat(data, parentValue = null) {
  return data.reduce(
    (arr, {
      label, value, description, children = [],
    }) => arr.concat(
      [
        {
          label,
          value,
          parentValue,
          description,
        },
      ],
      flat(children || [], value),
    ),
    [],
  );
}
// export function flat(data) {
//   return data.reduce((arr, {
//     label, value, description, parentValue, children = [],
//   }) => arr.concat([{
//     label, value, parentValue, description,
//   }], flat(children)), []);
// }
// 日期對應周幾
export function toWeek(date) {
  switch (date) {
    case 1:
      return '一';
    case 2:
      return '二';
    case 3:
      return '三';
    case 4:
      return '四';
    case 5:
      return '五';
    case 6:
      return '六';
    case 7:
      return '日';
    default:
      break;
  }
  return '日';
}
// 周幾轉換數字
export function dateToNumber(week) {
  switch (week) {
    case '一':
      return '1';
    case '二':
      return '2';
    case '三':
      return '3';
    case '四':
      return '4';
    case '五':
      return '5';
    case '六':
      return '6';
    case '日':
      return '7';
    default:
      break;
  }
  return '7';
}

function isObject(obj) {
  return Object.prototype.toString.call(obj) === '[object Object]';
}
// 實現深拷貝函數
export function deepClone(source, hash = new WeakMap()) {
  if (!isObject(source)) return source;
  if (hash.has(source)) return hash.get(source); // 新增代碼,查哈希表
  const target = Array.isArray(source) ? [] : {};
  hash.set(source, target); // 新增代碼,哈希表設值
  Object.keys(source).forEach((key) => {
    if (Object.prototype.hasOwnProperty.call(source, key)) {
      if (isObject(source[key])) {
        target[key] = deepClone(source[key], hash); // 新增代碼,傳入哈希表
      } else {
        target[key] = source[key];
      }
    }
  });
  return target;
}

再往前

/**
 * 優化 try-catch 的錯誤處理
 * @param {Function} asyncFun 異步函數
 * @param {Object} params
 * @returns [err, res] 返回被捕獲異常和成功的結果
 * demo:
    async loginOut(){
        let [err ,res] = await capturedAsync(LoginOut,{mobileLogin:true})
        if(err) return
    }
     export function LoginOut(params){
        return request.get('/a/logout',{params:params})
      }
 */
export const capturedAsync = async(asyncFun, params) => {
  try {
    const res = await asyncFun(params)
    return [null, res]
  } catch (err) {
    return [err, null]
  }
}

/**
 * 是否是空json對象
 * @param obj
 * @returns {boolean}
 */
export function isEmptyObject(obj) {
  return !obj || Object.keys(obj).length === 0
}

/**
 * 判斷是否為object對象,排除null
 * @param  {obj}  value 判斷的對像
 * @return {Boolean} true/false
 *
 */
function isObject(obj) {
  let type = typeof obj
  return type === "function" || (type === "object" && !!obj)
}

/**
 * 檢驗url是否合法
 * @param strUrl
 * @returns {boolean}
 */
export function isUrl(strUrl) {
  // ftp的user@
  /* eslint-disable no-useless-escape */
  let strRegex =
    "^((https|http|ftp|rtsp|mms)?://)" +
    "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?" +
    // IP形式的URL- 199.194.52.184
    "(([0-9]{1,3}.){3}[0-9]{1,3}" +
    // 允許IP和DOMAIN(域名)
    "|" +
    // 域名- www.
    "([0-9a-z_!~*'()-]+.)*" +
    // 二級域名
    "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]." +
    // first level domain- .com or .museum
    "[a-z]{2,6})" +
    // 端口- :80
    "(:[0-9]{1,4})?" +
    // a slash isn't required if there is no file name
    "((/?)|" +
    "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$"
  let re = new RegExp(strRegex)
  return re.test(strUrl)
}

/**
 * 獲取連接上面參數
 * @param name
 * @returns {*}
 */
export function getQueryString(name) {
  let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i")
  let r = window.location.search.substr(1).match(reg)
  if (r != null) return unescape(r[2])
  return null
}
/**
 * 垂直平滑滾動
 * @param {Number} pos 必傳 需要滾動到的位置
 * @param {Function} callback 滾動完成后執行的事件
 */
export function scrollTo(pos, callback) {
  let top = window.scrollY
  smooth()

  // 平滑滾動
  function smooth() {
    top = top + (pos - top) / 4
    // 臨界判斷,終止動畫
    if (Math.abs(top - pos) <= 1) {
      window.scrollTo(0, pos)
      callback && callback()
      return
    }
    window.scrollTo(0, top)
    requestAnimationFrame(smooth)
  }
}
/**
 * Merges two objects, giving the last one precedence
 * @param {Object} target
 * @param {(Object|Array)} source
 * @returns {Object}
 */
export function objectMerge(target, source) {
  if (typeof target !== "object") {
    target = {}
  }
  if (Array.isArray(source)) {
    return source.slice()
  }
  Object.keys(source).forEach(property => {
    const sourceProperty = source[property]
    if (typeof sourceProperty === "object") {
      target[property] = objectMerge(target[property], sourceProperty)
    } else {
      target[property] = sourceProperty
    }
  })
  return target
}

/**
 * @param {Function} func
 * @param {number} wait
 * @param {boolean} immediate
 * @return {*}
 */
export function debounce(func, wait, immediate) {
  let timeout, args, context, timestamp, result
  const later = function() {
    // 據上一次觸發時間間隔
    const last = +new Date() - timestamp
    // 上次被包裝函數被調用時間間隔 last 小于設定時間間隔 wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last)
    } else {
      timeout = null
      // 如果設定為immediate===true,因為開始邊界已經調用過了此處無需調用
      if (!immediate) {
        result = func.apply(context, args)
        if (!timeout) context = args = null
      }
    }
  }

  return function(...args) {
    context = this
    timestamp = +new Date()
    const callNow = immediate && !timeout
    // 如果延時不存在,重新設定延時
    if (!timeout) timeout = setTimeout(later, wait)
    if (callNow) {
      result = func.apply(context, args)
      context = args = null
    }
    return result
  }
}

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string}
 * index:parseTime(new Date(), '{y}-{m}-bsd5o550550j {h}:{i}:{s}')
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || "{y}-{m}-bsd5o550550j {h}:{i}:{s}"
  let date
  if (typeof time === "object") {
    date = time
  } else {
    if (typeof time === "string" && /^[0-9]+$/.test(time)) {
      time = parseInt(time)
    }
    if (typeof time === "number" && time.toString().length === 10) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if(key === "a") {
      return ["日", "一", "二", "三", "四", "五", "六"][value]
    }
    if(result.length > 0 && value < 10) {
      value = "0" + value
    }
    return value || 0
  })

  return time_str
}

// 終端判斷邏輯
const userAgent = navigator.userAgent
export const UA = {
  isWechat: !!userAgent.match(/MicroMessenger/gi), // 是否微信內
  isAlipay: !!userAgent.match(/aliapp/gi), // 支付寶
  isApp: !!userAgent.match(/leadeon/gi), // 是否app內
  isMobile: !!userAgent.match(/mobile/gi), // 是否移動端
  isBaiduMapp: /swan\//.test(window.navigator.userAgent) || /^webswan-/.test(window.name),
  isApple: !!userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), // 是否ios / mac 系統
  isAndroid: userAgent.indexOf("Android") > -1 || userAgent.indexOf("Linux") > -1, // 是否android
  is86App : !!window.cmcc_url || navigator.userAgent.toLocaleLowerCase().indexOf('10086app') > -1, // 是否是86app  
  isUniApp: !!userAgent.match(/(uniapp)/ig),                                                      //和家親
  // isPc:/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(window.navigator.userAgent) //判斷是否為移動端還是pc端,false是pc端,true是移動端
}
export function isWeChatMiniApp() {
  const ua = window.navigator.userAgent.toLowerCase()
  return new Promise(resolve => {
    if (ua.indexOf("micromessenger") == -1) {
      resolve(false)
    } else {
      let flag = false
      window.wx.miniProgram.getEnv(res => {
        flag = true
        if (res.miniprogram) {
          resolve(true)
        } else {
          resolve(false)
        }
      })
      setTimeout(()=> {
        if(!flag) {
          resolve(flag)
        }
      }, 2000)
    }
  })
}


/*
* 通過連接判斷當前是沙箱,預發環境,還是生產環境
* @return String test或者pro //test表示沙箱 staging表示預發,pro表示生產
* */
export function getJiYunEnvironment() {
  let jiYunEnvironment = ''
  if(window.location.hostname === 'sandbox.open.10086.cn') {
    jiYunEnvironment = 'test'
  } else if(window.location.hostname === 'dev.coc.10086.cn') {
    jiYunEnvironment = 'prod'
    if(window.location.href.indexOf("staging-coc2") > -1) {
      jiYunEnvironment = 'staging'        
    }
  } else {
    jiYunEnvironment = 'test'
  }
  return jiYunEnvironment
}


// 獲取指定的search參數
export const getUrlKey = function(name) {
  return (
    decodeURIComponent(
      (new RegExp("[?|&]" + name + "=" + "([^&;]+?)(&|#|;|$)").exec(
        location.href
      ) || ["", ""])[1].replace(/\+/g, "%20")
    ) || null
  )
}

/**
 * 日期格式化
 * @param value
 * @param format
 * @returns {*}
 * index:parseTime(new Date(), 'yyyy-MM-dd')
 */
export function dateFormat(value, format = 'yyyy-MM-dd') {
  if (typeof value === "string") {
    value = value.replace(/-/g, "/")
  }
  var t = new Date(value)
  if(isNaN(t)) return "" // 無效時間
  var o = {
    "M+": t.getMonth() + 1, // month
    "d+": t.getDate(), // day
    "h+": t.getHours(), // hour
    "m+": t.getMinutes(), // minute
    "s+": t.getSeconds(), // second
    "q+": Math.floor((t.getMonth() + 3) / 3), // quarter
    S: t.getMilliseconds() // millisecond
  }
  if (/(y+)/.test(format)) {
    format = format.replace(
      RegExp.$1,
      (t.getFullYear() + "").substr(4 - RegExp.$1.length)
    )
  }
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(format)) {
      format = format.replace(
        RegExp.$1,
        RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
      )
    }
  }
  return format
}

//跳轉頁面
export function jumpOut(url) {
  window.location.href = url
}

// 日志輸出,現網不輸出
export function dConsole(e) {
  console.log({...e})
}

// 返回介于 min 和 max(都包括)之間的隨機數
export function getRndInteger(min, max) {
  return Math.floor(Math.random() * (max - min + 1) ) + min
}


//判斷使用當前自己的4G網絡
export function isSelf4G() {
  // const connectionType = "bluetooth,ethernet,none,mixed,other,unknown,wifi,wimax"; //網絡類型
  // if (!(/windows|wifi/gi.test(navigator.userAgent.toLowerCase())||(!!navigator.connection&&!!navigator.connection.type&&connectionType.indexOf(navigator.connection.type)>-1))) {
  // 4G取號操作
  // }

  const types = ["bluetooth", "ethernet", "none", "mixed", "other", "unknown", "wifi", "wimax"],
    userAgent = navigator.userAgent.toLowerCase(),
    type = (navigator.connection && navigator.connection.type) || ''
  return !/windows|wifi/gi.test(userAgent) && !types.includes(type)
}

//判斷數據類型
export let types = {},
  typeNames = ['String', 'Object', 'Number', 'Array', 'Undefined', 'Function', 'Null', 'Symbol', 'Boolean', 'RegExp', 'BigInt']
typeNames.forEach(t => {
  types[`is${t}`] = function(obj) {
    return Object.prototype.toString.call(obj) === `[object ${t}]`
  }
})

原文鏈接:https://blog.csdn.net/m0_64207574/article/details/130790778

  • 上一篇:沒有了
  • 下一篇:沒有了
欄目分類
最近更新