网站首页 编程语言 正文
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}-{d} {h}:{i}:{s}')
*/
export function parseTime(time, cFormat) {
if (arguments.length === 0) {
return null
}
const format = cFormat || "{y}-{m}-{d} {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
- 上一篇:没有了
- 下一篇:没有了
相关推荐
- 2023-01-11 Android网络访问之Retrofit使用教程_Android
- 2022-07-18 Kotlin 正确退出 foreach、foreachIndexed 循环函数
- 2024-07-15 Postman:Body类型中的x-www-from-urlencoded参数可以接受GET请求吗?
- 2022-05-31 python库pydantic的简易入门教程_python
- 2022-07-16 Spring的隔离级别&事务传播属性&数据库隔离级别之间的联系
- 2022-08-28 elasticsearch-倒排索引原理
- 2022-05-04 python中使用多线程改进flask案例_python
- 2022-09-09 python 获取星期字符串的实例_python
- 栏目分类
-
- 最近更新
-
- window11 系统安装 yarn
- 超详细win安装深度学习环境2025年最新版(
- Linux 中运行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存储小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基础操作-- 运算符,流程控制 Flo
- 1. Int 和Integer 的区别,Jav
- spring @retryable不生效的一种
- Spring Security之认证信息的处理
- Spring Security之认证过滤器
- Spring Security概述快速入门
- Spring Security之配置体系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置权
- redisson分布式锁中waittime的设
- maven:解决release错误:Artif
- restTemplate使用总结
- Spring Security之安全异常处理
- MybatisPlus优雅实现加密?
- Spring ioc容器与Bean的生命周期。
- 【探索SpringCloud】服务发现-Nac
- Spring Security之基于HttpR
- Redis 底层数据结构-简单动态字符串(SD
- arthas操作spring被代理目标对象命令
- Spring中的单例模式应用详解
- 聊聊消息队列,发送消息的4种方式
- bootspring第三方资源配置管理
- GIT同步修改后的远程分支