值得收藏的前端开发必备工具类函数
/**
* 空值: [undefined, null, NaN, [], {}], 注意非空:0, false;
* @param {*} value
* @returns Boolean
*/
function isEmpty(value) {
switch (Object.prototype.toString.call(value)) {
case '[object Undefined]':
return value === void 0;
case '[object Null]':
return value === null;
case '[object Number]':
return isNaN(value);
case '[object String]':
return value === "";
case '[object Boolean]':
return false;
case '[object Object]':
return Object.keys(value).length === 0;
case '[object Array]':
return value.length === 0;
default:
return false;
}
}
/**
* el是否包含某个class
*/
export const hasClass = (el, className) => { let reg = new RegExp('(^|\\s)' + className + '(\\s|$)') return reg.test(el.className) }
/**
*el添加某个class
*/
export const addClass = (el, className) => { if (hasClass(el, className)) { return } let newClass = el.className.split(' ') newClass.push(className) el.className = newClass.join(' ') }
/**
* el去除某个class
*/
export const removeClass = (el, className) => { if (!hasClass(el, className)) { return } let reg = new RegExp('(^|\\s)' + className + '(\\s|$)', 'g') el.className = el.className.replace(reg, ' ') }
/**
*去除html标签
*/
export const removeHtmltag = (str) => {
return str.replace(/<[^>]+>/g, '')
}
/**
* 判断当前环境是否是手机端
*
* @return {Boolean} 返回结果
*
*/
export const isMobile = () => {
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
return true
} else {
return false
}
}
/**
* 断当前环境是否是微信环境
*
* @return {Boolean} 返回结果
*
*/
export const isWeixin = () => {
const ua = navigator.userAgent.toLowerCase();
if (ua.match(/MicroMessenger/i) === "micromessenger") {
return true;
} else {
return false;
}
}
/**
* 检测浏览器是否放大
*
* @param {Boolean } rsize 是否返回具体放大数值,默认否
* @return {Boolean | Number} 返回结果
*
*/
export const detectZoom = rsize => {
let ratio = 0
const screen = window.screen
const ua = navigator.userAgent.toLowerCase()
if (window.devicePixelRatio) {
ratio = window.devicePixelRatio
} else if (~ua.indexOf('msie')) {
if (screen.deviceXDPI && screen.logicalXDPI) ratio = screen.deviceXDPI / screen.logicalXDPI
} else if (window.outerWidth && window.innerWidth) {
ratio = window.outerWidth / window.innerWidth
}
if (ratio) ratio = Math.round(ratio * 100)
return rsize ? ratio : ratio === 100
}
// 例如:http://localhost:8080/?token=rTyJ7bcRb7KU4DMcWo4216&roleId=512213631174180864
/**
* 获取URL参数
* @param variable
* @returns {string | Boolean}
*/
export function getQueryVariable(variable) {
const query = window.location.search.substring(1)
const vars = query.split('&')
for (const item of vars) {
const pair = item.split('=')
if (pair[0] === variable) {
return pair[1]
}
}
return false
}
/**
* 获取hash模式地址url参数
* 例如:http://localhost:8080/#/?token=rTyJ7bcRb7KU4DMcWo4216&roleId=512213631174180864
*
* @param {String} name
* @return {Boolean | String} 返回获取值
*
*/
export const getUrlHashParam = name => {
const w = window.location.hash.indexOf("?");
const query = window.location.hash.substring(w + 1);
const vars = query.split("&");
for (let i = 0; i < vars.length; i++) {
const pair = vars[i].split("=");
if (pair[0] == name) {
return pair[1];
}
}
return false;
}
/**
* 时间戳转换
*
* @param {Number} date 时间戳
* @param {String} fmt 时间显示格式,例如 yyyy-MM-dd HH:mm:ss
* @return {String} fmt 返回转换后的时间 ,formatDate(value, "yyyy-MM-dd hh: mm : ss")
*
*/
export const formatDate = (date, fmt) => {
date = new Date(date);
if (isNaN(date.getDate())) return date;
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(
RegExp.$1,
(date.getFullYear() + "").substr(4 - RegExp.$1.length)
);
}
let o = {
"M+": date.getMonth() + 1,
"d+": date.getDate(),
"h+": date.getHours(),
"m+": date.getMinutes(),
"s+": date.getSeconds()
};
for (let k in o) {
if (new RegExp(`(${k})`).test(fmt)) {
let str = o[k] + "";
fmt = fmt.replace(
RegExp.$1,
RegExp.$1.length === 1 ? str : ("00" + str).substr(str.length)
);
}
}
return fmt;
};
/**
* 时间戳转换成什么之前
*
* @param {Number} times 时间戳
* @return {String} 返回结果,timeAgoLabel(1606273724459) 输出:刚刚
*
*/
export const timeAgoLabel = times => {
let nowTimes = new Date().getTime()
let diffSecond = (nowTimes - times) / 1000
let agoLabel = ''
if (diffSecond < 60) {
agoLabel = '刚刚'
} else if (diffSecond < 60 * 60) {
agoLabel = Math.floor(diffSecond / 60) + '分钟前'
} else if (diffSecond < 60 * 60 * 24) {
agoLabel = Math.floor(diffSecond / 3600) + '小时前'
} else if (diffSecond < 60 * 60 * 24 * 30) {
agoLabel = Math.floor(diffSecond / (3600 * 24)) + '天前'
} else if (diffSecond < 3600 * 24 * 30 * 12) {
agoLabel = Math.floor(diffSecond / (3600 * 24 * 30)) + '月前'
} else {
agoLabel = Math.floor(diffSecond / (3600 * 24 * 30 * 12)) + '年前'
}
return agoLabel
}
/**
* 生成任意位数随机数(数字)
*
* @param {Number} n 可选长度位数
* @return {Number} 返回随机值
*
*/
export const randomNumber = n => {
let rnd = '';
for (let i = 0; i < n; i++) {
rnd += Math.floor(Math.random() * 10);
}
return rnd;
}
/**
* 随机生成一个自定义长度,不重复的字母加数字组合,可用来做id标识
*
* @param {Number} randomLength 可选长度位数,默认10
* @return {String} 返回随机值
*
*/
export const randomId = (randomLength = 10) => {
return Number(Math.random().toString().substr(3, randomLength) + Date.now()).toString(36)
}
/**
* 文件大小换算成单位
*
* @param {Number} bytes 大小
* @param {String} units 可选单位,默认metric
* @param {Number} precision 可选位数,数值精度保留几位小数点,默认1
* @return {String} 返回带单位值,byteSize(1580),输出1.6 kB
*
*/
export const byteSize = (bytes, units = 'metric', precision = 1) => {
let value = '',
unit = ''
const base = units === 'metric' || units === 'metric_octet' ? 1000 : 1024
const table = [
{ expFrom: 0, expTo: 1, metric: 'B', iec: 'B', metric_octet: 'o', iec_octet: 'o' },
{ expFrom: 1, expTo: 2, metric: 'kB', iec: 'KiB', metric_octet: 'ko', iec_octet: 'Kio' },
{ expFrom: 2, expTo: 3, metric: 'MB', iec: 'MiB', metric_octet: 'Mo', iec_octet: 'Mio' },
{ expFrom: 3, expTo: 4, metric: 'GB', iec: 'GiB', metric_octet: 'Go', iec_octet: 'Gio' },
{ expFrom: 4, expTo: 5, metric: 'TB', iec: 'TiB', metric_octet: 'To', iec_octet: 'Tio' },
{ expFrom: 5, expTo: 6, metric: 'PB', iec: 'PiB', metric_octet: 'Po', iec_octet: 'Pio' },
{ expFrom: 6, expTo: 7, metric: 'EB', iec: 'EiB', metric_octet: 'Eo', iec_octet: 'Eio' },
{ expFrom: 7, expTo: 8, metric: 'ZB', iec: 'ZiB', metric_octet: 'Zo', iec_octet: 'Zio' },
{ expFrom: 8, expTo: 9, metric: 'YB', iec: 'YiB', metric_octet: 'Yo', iec_octet: 'Yio' }
]
for (let i = 0; i < table.length; i++) {
const lower = Math.pow(base, table[i].expFrom)
const upper = Math.pow(base, table[i].expTo)
if (bytes >= lower && bytes < upper) {
const retUnit = table[i][units]
if (i === 0) {
value = String(bytes)
unit = retUnit
break;
} else {
value = (bytes / lower).toFixed(precision)
unit = retUnit
break;
}
}
}
return `${value} ${unit}`.trim()
}
/**
* 平滑滚动到页面顶部
*
*/
export const scrollToTop = () => {
const c = document.documentElement.scrollTop || document.body.scrollTop;
if (c > 0) {
window.requestAnimationFrame(scrollToTop);
window.scrollTo(0, c - c / 8);
}
}
/**
* 滚动到页面底部
*/
export const scrollToBottom = () => {
window.scrollTo(0, document.documentElement.clientHeight);
}
/**
*获取可视窗口高度
*/
export const getClientHeight = () => {
let clientHeight = 0;
if (document.body.clientHeight && document.documentElement.clientHeight) {
clientHeight = (document.body.clientHeight < document.documentElement.clientHeight) ? document.body.clientHeight : document.documentElement.clientHeight;
} else {
clientHeight = (document.body.clientHeight > document.documentElement.clientHeight) ? document.body.clientHeight : document.documentElement.clientHeight;
}
return clientHeight;
}
/**
*数字千分位分隔
*/
export const format = (n) => {
let num = n.toString();
let len = num.length;
if (len <= 3) {
return num;
} else {
let temp = '';
let remainder = len % 3;
if (remainder > 0) { // 不是3的整数倍
return num.slice(0, remainder) + ',' + num.slice(remainder, len).match(/\d{3}/g).join(',') + temp;
} else { // 3的整数倍
return num.slice(0, len).match(/\d{3}/g).join(',') + temp;
}
}
}
/**
* 全角转换为半角
*/
export const toCDB = (str) => {
let result = "";
for (let i = 0; i < str.length; i++) {
code = str.charCodeAt(i);
if (code >= 65281 && code <= 65374) {
result += String.fromCharCode(str.charCodeAt(i) - 65248);
} else if (code == 12288) {
result += String.fromCharCode(str.charCodeAt(i) - 12288 + 32);
} else {
result += str.charAt(i);
}
}
return result;
}
/**
* 半角转换为全角
*/
export const toDBC = (str) => {
let result = "";
for (let i = 0; i < str.length; i++) {
code = str.charCodeAt(i);
if (code >= 33 && code <= 126) {
result += String.fromCharCode(str.charCodeAt(i) + 65248);
} else if (code == 32) {
result += String.fromCharCode(str.charCodeAt(i) + 12288 - 32);
} else {
result += str.charAt(i);
}
}
return result;
}
/**
* 数字转化为大写金额
*/
export const digitUppercase = (n) => {
const fraction = ['角', '分'];
const digit = [
'零', '壹', '贰', '叁', '肆',
'伍', '陆', '柒', '捌', '玖'
];
const unit = [
['元', '万', '亿'],
['', '拾', '佰', '仟']
];
n = Math.abs(n);
let s = '';
for (let i = 0; i < fraction.length; i++) {
s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '');
}
s = s || '整';
n = Math.floor(n);
for (let i = 0; i < unit[0].length && n > 0; i++) {
let p = '';
for (let j = 0; j < unit[1].length && n > 0; j++) {
p = digit[n % 10] + unit[1][j] + p;
n = Math.floor(n / 10);
}
s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s;
}
return s.replace(/(零.)*零元/, '元')
.replace(/(零.)+/g, '零')
.replace(/^整$/, '零元整');
};
/**
* 数字转化为中文数字
*/
export const intToChinese = (value) => {
const str = String(value);
const len = str.length - 1;
const idxs = ['', '十', '百', '千', '万', '十', '百', '千', '亿', '十', '百', '千', '万', '十', '百', '千', '亿'];
const num = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
return str.replace(/([1-9]|0+)/g, ($, $1, idx, full) => {
let pos = 0;
if ($1[0] !== '0') {
pos = len - idx;
if (idx == 0 && $1[0] == 1 && idxs[len - idx] == '十') {
return idxs[len - idx];
}
return num[$1[0]] + idxs[len - idx];
} else {
let left = len - idx;
let right = len - idx + $1.length;
if (Math.floor(right / 4) - Math.floor(left / 4) > 0) {
pos = left - left % 4;
}
if (pos) {
return idxs[pos] + num[$1[0]];
} else if (idx + $1.length >= len) {
return '';
} else {
return num[$1[0]]
}
}
});
}
/**
* 存储loalStorage
*/
export const loalStorageSet = (key, value) => {
if (!key) return;
if (typeof value !== 'string') {
value = JSON.stringify(value);
}
window.localStorage.setItem(key, value);
};
export const loalStorageGet = (key) => {
if (!key) return;
return window.localStorage.getItem(key);
};
export const loalStorageRemove = (key) => {
if (!key) return;
window.localStorage.removeItem(key);
};
export const sessionStorageSet = (key, value) => {
if (!key) return;
if (typeof value !== 'string') {
value = JSON.stringify(value);
}
window.sessionStorage.setItem(key, value)
};
export const sessionStorageGet = (key) => {
if (!key) return;
return window.sessionStorage.getItem(key)
};
export const sessionStorageRemove = (key) => {
if (!key) return;
window.sessionStorage.removeItem(key)
};