心里认定了一个女孩 就要好好的珍惜对待她,人生不容辜负,你必须要更加努力 。加油 骚年
JS 常用功能方法集合,持续会更新
/**
*[获取URL中的参数名及参数值的集合]
* 示例URL:http://htmlJsTest/getrequest.html?uid=admin&rid=1&fid=2&name=小明
* @param {[string]} urlStr [当该参数不为空的时候,则解析该url中的参数集合]
* @return {[string]} [参数集合]
*/
export function GetRequest(urlStr) {
if (typeof urlStr == "undefined") {
var url = decodeURI(location.search); //获取url中"?"符后的字符串
} else {
var url = "?" + urlStr.split("?")[1];
}
var theRequest = new Object();
if (url.indexOf("?") != -1) {
var str = url.substr(1);
let strs = str.split("&");
for (var i = 0; i < strs.length; i++) {
theRequest[strs[i].split("=")[0]] = decodeURI(strs[i].split("=")[1]);
}
}
return theRequest;
}
// 获取url中的参数
export function urlParamToObj(url, key) {
var reg = /(?:\?|\&)([^=&?]+)=([^=&?]+)/g,
res = {};
url.replace(reg, function($, $1, $2) {
res[$1] = decodeURIComponent($2);
});
if (key === void 0) return res;
if (key in res) return res[key];
}
/**
* @description 根据主键删除数组中的元素 123
* 比如:deleteByKeys(fileList, 'uid', [file.uid]); file.uid当前文件的id 根据这个 id 删除数组中的这个
* @param array 原数组
* @param keyField 主键字段
* @param keyValues 主键值
*/
export function deleteByKeys(array, keyField, keyValues) {
if (!array || !keyField || !keyValues) return;
if (!Array.isArray(keyValues)) keyValues = [keyValues];
keyValues.forEach((item) => {
const param = {};
param[keyField] = item;
let index = -1;
do {
index = getIndexByObject(array, param);
if (index != -1) array.splice(index, 1);
} while (index > -1);
});
}
export function getIndexByObject(array, paramObject) {
if (array == undefined || array == null) return -1;
let equalFlag = false;
let index = -1;
for (let i = 0; i < array.length; i++) {
equalFlag = true;
const item = array[i];
for (const property in paramObject) {
if (item[property] != paramObject[property]) {
equalFlag = false;
break;
}
}
if (equalFlag) {
index = i;
break;
}
}
return index;
}
// 校验数据类型
export const typeOf = function(obj) {
return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase()
}
//防抖
export const debounce = (() => {
let timer = null
return (callback, wait = 800) => {
timer&&clearTimeout(timer)
timer = setTimeout(callback, wait)
}
})()
//如 防抖vue 中使用
/**
methods: {
loadList() {
debounce(() => {
console.log('加载数据')
}, 500)
}
}
*/
//节流
export const throttle = (() => {
let last = 0
return (callback, wait = 800) => {
let now = +new Date()
if (now - last > wait) {
callback()
last = now
}
}
})()
//判断数组是否为空
export function isEmpty(array) {
return !array || (Array.isArray(array) && array.length == 0);
}
//银行卡 每四位中间加一个空格
export function bankRe(v) {
if (/\S{5}/.test(v)) {
return v.replace(/\s/g, '').replace(/(.{4})/g, "$1 ");
}
}
// 隐藏银行卡中间号码包含空格
export function hideBankCard(value){
if (value && value.length > 8) {
return `${value.substring(0, 4)} ${"*".repeat(value.length - 8).replace(/(.{4})/g, `$1 `)}${value.length % 4 ? " " : ""}${value.slice(-4)}`;
}
return value;
}
console.log(hideBankCard(6212261611110000222))
//打印结果 6212 **** **** *** 0222
// 隐藏银行卡中间号码不包含空格
export function hideBankCard(value){
if(value&&value.length>8) {
let reg = /^(\d{4})(\d*)(\d{4})$/;
let str = value.replace(reg, (a, b, c, d)=> {
return b + c.replace(/\d/g, "*") + d;
});
return str
}else {
return value
}
}
console.log(hideBankCard('6212261611110000222'));
//打印结果 6212***********0222
// 开启全屏
export const launchFullscreen = () => {
//获取当前是否全屏展示
let full = document.fullscreenElement;
if (!full) {
document.documentElement.requestFullscreen();
} else {
document.exitFullscreen();
}
}
/**
* @description. [大小写转换]
* str 待转换的字符串
* type 1-全大写 2-全小写 3-首字母大写
*/
export const turnCase = (str, type) => {
switch (type) {
case 1:
return str.toUpperCase()
case 2:
return str.toLowerCase()
case 3:
//return str[0].toUpperCase() + str.substr(1).toLowerCase() // substr 已不推荐使用
return str[0].toUpperCase() + str.substring(1).toLowerCase()
default:
return str
}
}
/**
*@description 判断手机是Andoird还是IOS
* 1: ios
* 2: android
* 3: 其它
*/
export const getOSType=() => {
let u = navigator.userAgent, app = navigator.appVersion;
let isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1;
let isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
if (isIOS) {
return 1;
}
if (isAndroid) {
return 2;
}
return 3;
}
// 数组去重
export const distinct = (arr = testArr) => {
return arr.filter((v, i, array) => array.indexOf(v) === i)
}
var list = [1,1,2,3,3,2,1,2,31,12,31,2];
console.log(distinct(list));
/**
* @description 数组对象根据字段去重
* arr 要去重的数组
* key 根据去重的字段名
*/
export const uniqueArrayObject = (arr = [], key = 'id') => {
if (arr.length === 0) return
let list = []
const map = {}
arr.forEach((item) => {
if (!map[item[key]]) {
map[item[key]] = item
}
})
list = Object.values(map)
return list
}
// 示列 uniqueArrayObject(responseList, 'id')
// 滚动到页面顶部
export const scrollToTop = () => {
const height = document.documentElement.scrollTop || document.body.scrollTop;
if (height > 0) {
window.requestAnimationFrame(scrollToTop);
window.scrollTo(0, height - height / 8);
}
}
//滚动到元素位置
export const smoothScroll = element =>{
document.querySelector(element).scrollIntoView({
behavior: 'smooth'
});
};
// smoothScroll('#target'); // 平滑滚动到 ID 为 target 的元素
//uuid
export const uuid = () => {
const temp_url = URL.createObjectURL(new Blob())
const uuid = temp_url.toString()
URL.revokeObjectURL(temp_url) //释放这个url
return uuid.substring(uuid.lastIndexOf('/') + 1)
}
// 根据参数获取间隔年月日 123
// 获取间隔天数
export function getIntervalDate(n) {
const dd = new Date();
// 获取n天后的日期
dd.setDate(dd.getDate() + n * 1);
const year = dd.getFullYear();
// 获取当前月份的日期,不足10补0
const mon =
dd.getMonth() + 1 < 10 ? `0${dd.getMonth() + 1}` : dd.getMonth() + 1;
// 获取当前几号,不足10补0
const day = dd.getDate() < 10 ? `0${dd.getDate()}` : dd.getDate();
const _date = `${year}-${mon}-${day}`;
return _date;
}
//数字转换为大写中文
export function digitUppercase(money) {
//汉字的数字
var cnNums = new Array('零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖');
//基本单位
var cnIntRadice = new Array('', '拾', '佰', '仟');
//对应整数部分扩展单位
var cnIntUnits = new Array('', '万', '亿', '兆');
//对应小数部分单位
var cnDecUnits = new Array('角', '分', '毫', '厘');
//整数金额时后面跟的字符
var cnInteger = '整';
//整型完以后的单位
var cnIntLast = '元';
//最大处理的数字
var maxNum = 999999999999999.9999;
//金额整数部分
var integerNum;
//金额小数部分
var decimalNum;
//输出的中文金额字符串
var chineseStr = '';
//分离金额后用的数组,预定义
var parts;
if (money == '') { return ''; }
money = parseFloat(money);
if (money >= maxNum) {
//超出最大处理数字
return '';
}
if (money == 0) {
chineseStr = cnNums[0] + cnIntLast + cnInteger;
return chineseStr;
}
//转换为字符串
money = money.toString();
if (money.indexOf('.') == -1) {
integerNum = money;
decimalNum = '';
} else {
parts = money.split('.');
integerNum = parts[0];
decimalNum = parts[1].substr(0, 4);
}
//获取整型部分转换
if (parseInt(integerNum, 10) > 0) {
var zeroCount = 0;
var IntLen = integerNum.length;
for (var i = 0; i < IntLen; i++) {
var n = integerNum.substr(i, 1);
var p = IntLen - i - 1;
var q = p / 4;
var m = p % 4;
if (n == '0') {
zeroCount++;
} else {
if (zeroCount > 0) {
chineseStr += cnNums[0];
}
//归零
zeroCount = 0;
chineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
}
if (m == 0 && zeroCount < 4) {
chineseStr += cnIntUnits[q];
}
}
chineseStr += cnIntLast;
}
//小数部分
if (decimalNum != '') {
var decLen = decimalNum.length;
for (var i = 0; i < decLen; i++) {
var n = decimalNum.substr(i, 1);
if (n != '0') {
chineseStr += cnNums[Number(n)] + cnDecUnits[i];
}
}
}
if (chineseStr == '') {
chineseStr += cnNums[0] + cnIntLast + cnInteger;
} else if (decimalNum == '') {
chineseStr += cnInteger;
}
return chineseStr;
}
//
/**
*@description [金额格式化]
*{number} number:要格式化的数字
*{number} decimals:保留几位小数
*{string} dec_point:小数点符号
*{number} number:要格式化的数字
*{string} thousands_sep:千分位符号
*/
export const moneyFormat = (number, decimals, dec_point, thousands_sep) => {
number = (number + '').replace(/[^0-9+-Ee.]/g, '')
const n = !isFinite(+number) ? 0 : +number
const prec = !isFinite(+decimals) ? 2 : Math.abs(decimals)
const sep = typeof thousands_sep === 'undefined' ? ',' : thousands_sep
const dec = typeof dec_point === 'undefined' ? '.' : dec_point
let s = ''
const toFixedFix = function(n, prec) {
const k = Math.pow(10, prec)
return '' + Math.ceil(n * k) / k
}
s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.')
const re = /(-?\d+)(\d{3})/
while (re.test(s[0])) {
s[0] = s[0].replace(re, '$1' + sep + '$2')
}
if ((s[1] || '').length < prec) {
s[1] = s[1] || ''
s[1] += new Array(prec - s[1].length + 1).join('0')
}
return s.join(dec)
}
// 增加千位符
export function toThousands(num) {
if (num) {
var str = num.toString()
var reg = str.indexOf('.') > -1 ? /(\d)(?=(\d{3})+\.)/g : /(\d)(?=(?:\d{3})+$)/g
return str.replace(reg, '$1,')
} else {
return num
}
}
/**
* 截取指定字节的字符串
* @param str 要截取的字符穿
* @param len 要截取的长度,根据字节计算
* @param suffix 截取前len个后,其余的字符的替换字符,一般用“…”
* @returns {*}
*/
export function cutString(str, len, suffix) {
if (!str) return "";
if (len <= 0) return "";
if (!suffix) suffix = "";
var templen = 0;
for (var i = 0; i < str.length; i++) {
if (str.charCodeAt(i) > 255) {
templen += 2;
} else {
templen++
}
if (templen == len) {
return str.substring(0, i + 1) + suffix;
} else if (templen > len) {
return str.substring(0, i) + suffix;
}
}
return str;
}
// 表单校验手机号码
export function checkPhone(rule, value, callback) {
if (/^1[0-9]{10}$/.test(value)) {
callback()
} else {
callback(new Error('请输入正确的11位手机号码'))
}
}
// 手机号中间四位显示 * 号
export function hideMobile(mobile) {
return mobile.replace(/^(\d{3})\d{4}(\d{4})$/, "$1****$2")
}
// hideMobile('14456565656')
// 表单校验身份证号码
export function checkIdentity(rule, value, callback) {
if (/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(value)) {
callback()
} else {
callback(new Error('请输入正确的身份证号码'))
}
}
// 表单验证邮箱
export function checkEmil(rule, value, callback) {
if (/^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/.test(value)) {
callback()
} else {
callback(new Error('请输入正确的邮箱'))
}
}
// 计算表格List某个字段Number总和
//比如:calculateListSum(this.ruleForm.detailList, 'regionIncome', 2)
export function calculateListSum(array, field, fixedNum) {
if (!(array && array.length)) return Number(0).toFixed(fixedNum)
else {
const result = (array.reduce((pre, current) => pre + Number(current[field] || 0), 0)).toFixed(fixedNum)
return result
}
}
// 校验表格List某个字段是否重复
export function checkDuplicate(list, field) {
let map = new Map()
for (let i = 0; i < list.length; i++) {
if (map.has(list[i][field])) {
return true
} else {
map.set(list[i][field], i)
if (map.size == list.length) {
return false
}
}
}
}
/**
* @description 根据value值进行list对应的枚举转换
* @param list 枚举数组
* @param value 目标value值
* @param keyField 主键字段
* 比如 getEnumTextByList(typeOptions, record.type, "label")
**/
export function getEnumTextByList(list, value, keyField) {
let result = list.find(item => item.value == value)
return result && result[keyField]
}
//存储操作
class MyCache {
constructor(isLocal = true) {
this.storage = isLocal ? localStorage : sessionStorage
}
setItem(key, value) {
if (typeof (value) === 'object') value = JSON.stringify(value)
this.storage.setItem(key, value)
}
getItem(key) {
try {
return JSON.parse(this.storage.getItem(key))
} catch (err) {
return this.storage.getItem(key)
}
}
removeItem(key) {
this.storage.removeItem(key)
}
clear() {
this.storage.clear()
}
key(index) {
return this.storage.key(index)
}
length() {
return this.storage.length
}
}
const localCache = new MyCache()
const sessionCache = new MyCache(false)
export { localCache, sessionCache }
//示例
// localCache.getItem('user')
// sessionCache.setItem('name','树哥')
// sessionCache.getItem('token')
// localCache.clear()
/**
* @description. 下载文件
* api 接口
* params 请求参数
* fileName 文件名
*/
const downloadFile = (api, params, fileName, type = 'get') => {
axios({
method: type,
url: api,
responseType: 'blob',
params: params
}).then((res) => {
let str = res.headers['content-disposition']
if (!res || !str) {
return
}
let suffix = ''
// 截取文件名和文件类型
if (str.lastIndexOf('.')) {
fileName ? '' : fileName = decodeURI(str.substring(str.indexOf('=') + 1, str.lastIndexOf('.')))
suffix = str.substring(str.lastIndexOf('.'), str.length)
}
// 如果支持微软的文件下载方式(ie10+浏览器)
if (window.navigator.msSaveBlob) {
try {
const blobObject = new Blob([res.data]);
window.navigator.msSaveBlob(blobObject, fileName + suffix);
} catch (e) {
console.log(e);
}
} else {
// 其他浏览器
let url = window.URL.createObjectURL(res.data)
let link = document.createElement('a')
link.style.display = 'none'
link.href = url
link.setAttribute('download', fileName + suffix)
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
window.URL.revokeObjectURL(link.href);
}
}).catch((err) => {
console.log(err.message);
})
}
// 示例: downloadFile('/api/download', {id}, '文件名')
// 遍历树节点
export const foreachTree = (data, callback, childrenName = 'children') => {
for (let i = 0; i < data.length; i++) {
callback(data[i])
if (data[i][childrenName] && data[i][childrenName].length > 0) {
foreachTree(data[i][childrenName], callback, childrenName)
}
}
}
/** 示例:假设我们要从树状结构数据中查找 id 为 9 的节点
const data = [{
id: 1,
label: '一级 1',
children: [{
id: 4,
label: '二级 1-1',
children: [{
id: 9,
label: '三级 1-1-1'
}, {
id: 10,
label: '三级 1-1-2'
}]
}]
}, {
id: 2,
label: '一级 2',
children: [{
id: 5,
label: '二级 2-1'
}, {
id: 6,
label: '二级 2-2'
}]
}, {
id: 3,
label: '一级 3',
children: [{
id: 7,
label: '二级 3-1'
}, {
id: 8,
label: '二级 3-2'
}]
}],
let result
foreachTree(data, (item) => {
if (item.id === 9) {
result = item
}
})
console.log('result', result) // {id: 9,label: "三级 1-1-1"}
*/
后面会持续更新
如有不足之处请指出 或直接联系邮箱 [email protected] 谢谢