格式化日期
function formatDate(date) {
if (date) {
const year = date.getFullYear()
const month =
date.getMonth() + 1 < 10
? '0' + (date.getMonth() + 1)
: date.getMonth() + 1
const day =
date.getDate() + 1 < 10 ? '0' + date.getDate() : date.getDate()
return (
year +
'/' +
month +
'/' +
day
)
} else {
return null
}
}
获取url参数
function getParams(url) {
const res = {}
if (url.includes('?')) {
const str = url.split('?')[1]
const arr = str.split('&')
arr.forEach(item => {
const key = item.split('=')[0]
const val = item.split('=')[1]
res[key] = decodeURIComponent(val) // 解码
})
}
return res
}
拼接对象为get请求字符串
function formatGetUri(obj) {
const params = []
Object.keys(obj).forEach((key) => {
const value = obj[key]
if (typeof value === 'undefined' || value === null || value === '') {
return
} else {
params.push([key, encodeURIComponent(value)].join('='))
}
})
return '?' + params.join('&')
}
金额显示
function parseToMoney(num) {
num = parseFloat(num.toFixed(3));
let [integer, decimal] = String.prototype.split.call(num, '.');
integer = integer.replace(/\d(?=(\d{3})+$)/g, '$&,');
return integer + '.' + (decimal ? decimal : '');
}
判断是否是电话号码
function isPhone(tel) {
var regx = /^1[34578]\d{9}$/;
return regx.test(tel);
}
判断是否是邮箱
function isEmail(email) {
var regx = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+$/;
return regx.test(email);
}
判断是否是身份证
function isCardNo(number) {
var regx = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
return regx.test(number);
}
基于Promise封装Ajax
function ajax(url, method) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest()
xhr.open(url, method, true)
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
resolve(xhr.responseText)
} else if (xhr.status === 404) {
reject(new Error('404'))
}
} else {
reject('请求数据失败')
}
}
xhr.send(null)
})
}
防抖
const debounce = (func, wait = 50) => {
let timer = 0
return function(...args) {
if (timer) clearTimeout(timer)
timer = setTimeout(() => {
func.apply(this, args)
}, wait)
}
}
节流
const throttle = (func, wait = 50) => {
let lastTime = 0
return function(...args) {
let now = +new Date()
if (now - lastTime > wait) {
lastTime = now
func.apply(this, args)
}
}
}
setInterval(
throttle(() => {
console.log(1)
}, 500),
1
)