/**
* 清空对象
* @param obj
* @returns {boolean|*}
*/
export function clearObj(obj) {
// 判断是不是对象
if (!Object.prototype.toString.call(obj) == '[object Object]') {
return false
}
for (const key in obj) {
if (Object.prototype.toString.call(obj[key]) == '[object Object]') {
// 处理多级非空对象
if (Object.keys(obj[key]).length > 0) {
clearObj(obj[key])
}
} else if (Array.isArray(obj[key])) {
// 数组置空
obj[key] = []
} else {
// 其他类型, 如果以下对象没有包含类型的将会是 undefined
let dataType = {
number: 0,
string: '',
boolean: false,
function: () => {}
}
let _key = typeof obj[key]
obj[key] = dataType[_key]
}
}
return obj
}
/**
* 空值: [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
}
/**
* 获取普通地址url参数
* 例如:http://localhost:8080/?token=rTyJ7bcRb7KU4DMcWo4216&roleId=512213631174180864
*
* @param {String} name
* @return {Boolean | String} 返回获取值
*
*/
export const getUrlParam = name =>{
const reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
const r = window.location.search.substr(1).match(reg);
if (r != null) return decodeURI(r[2]); 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)
};
值得收藏的前端开发必备工具类函数
toyiye 2024-07-02 03:01 13 浏览 0 评论
相关推荐
- 为何越来越多的编程语言使用JSON(为什么编程)
-
JSON是JavascriptObjectNotation的缩写,意思是Javascript对象表示法,是一种易于人类阅读和对编程友好的文本数据传递方法,是JavaScript语言规范定义的一个子...
- 何时在数据库中使用 JSON(数据库用json格式存储)
-
在本文中,您将了解何时应考虑将JSON数据类型添加到表中以及何时应避免使用它们。每天?分享?最新?软件?开发?,Devops,敏捷?,测试?以及?项目?管理?最新?,最热门?的?文章?,每天?花?...
- MySQL 从零开始:05 数据类型(mysql数据类型有哪些,并举例)
-
前面的讲解中已经接触到了表的创建,表的创建是对字段的声明,比如:上述语句声明了字段的名称、类型、所占空间、默认值和是否可以为空等信息。其中的int、varchar、char和decimal都...
- JSON对象花样进阶(json格式对象)
-
一、引言在现代Web开发中,JSON(JavaScriptObjectNotation)已经成为数据交换的标准格式。无论是从前端向后端发送数据,还是从后端接收数据,JSON都是不可或缺的一部分。...
- 深入理解 JSON 和 Form-data(json和formdata提交区别)
-
在讨论现代网络开发与API设计的语境下,理解客户端和服务器间如何有效且可靠地交换数据变得尤为关键。这里,特别值得关注的是两种主流数据格式:...
- JSON 语法(json 语法 priority)
-
JSON语法是JavaScript语法的子集。JSON语法规则JSON语法是JavaScript对象表示法语法的子集。数据在名称/值对中数据由逗号分隔花括号保存对象方括号保存数组JS...
- JSON语法详解(json的语法规则)
-
JSON语法规则JSON语法是JavaScript对象表示法语法的子集。数据在名称/值对中数据由逗号分隔大括号保存对象中括号保存数组注意:json的key是字符串,且必须是双引号,不能是单引号...
- MySQL JSON数据类型操作(mysql的json)
-
概述mysql自5.7.8版本开始,就支持了json结构的数据存储和查询,这表明了mysql也在不断的学习和增加nosql数据库的有点。但mysql毕竟是关系型数据库,在处理json这种非结构化的数据...
- JSON的数据模式(json数据格式示例)
-
像XML模式一样,JSON数据格式也有Schema,这是一个基于JSON格式的规范。JSON模式也以JSON格式编写。它用于验证JSON数据。JSON模式示例以下代码显示了基本的JSON模式。{"...
- 前端学习——JSON格式详解(后端json格式)
-
JSON(JavaScriptObjectNotation)是一种轻量级的数据交换格式。易于人阅读和编写。同时也易于机器解析和生成。它基于JavaScriptProgrammingLa...
- 什么是 JSON:详解 JSON 及其优势(什么叫json)
-
现在程序员还有谁不知道JSON吗?无论对于前端还是后端,JSON都是一种常见的数据格式。那么JSON到底是什么呢?JSON的定义...
- PostgreSQL JSON 类型:处理结构化数据
-
PostgreSQL提供JSON类型,以存储结构化数据。JSON是一种开放的数据格式,可用于存储各种类型的值。什么是JSON类型?JSON类型表示JSON(JavaScriptO...
- JavaScript:JSON、三种包装类(javascript 包)
-
JOSN:我们希望可以将一个对象在不同的语言中进行传递,以达到通信的目的,最佳方式就是将一个对象转换为字符串的形式JSON(JavaScriptObjectNotation)-JS的对象表示法...
- Python数据分析 只要1分钟 教你玩转JSON 全程干货
-
Json简介:Json,全名JavaScriptObjectNotation,JSON(JavaScriptObjectNotation(记号、标记))是一种轻量级的数据交换格式。它基于J...
- 比较一下JSON与XML两种数据格式?(json和xml哪个好)
-
JSON(JavaScriptObjectNotation)和XML(eXtensibleMarkupLanguage)是在日常开发中比较常用的两种数据格式,它们主要的作用就是用来进行数据的传...
你 发表评论:
欢迎- 一周热门
- 最近发表
- 标签列表
-
- r语言矩阵 (127)
- browsererror (114)
- exportexcel (119)
- cv2.bitwise_not (137)
- dump命令 (128)
- es6concat (126)
- heapify (127)
- java.security.egd (130)
- javax.annotation (117)
- jsstringsplit (117)
- js数字 (115)
- maven编译 (132)
- mysqlleft (128)
- nodejsbuffer (149)
- org.apache.commons.httpclient (126)
- org.jsoup (141)
- org.springframework.web (128)
- robotframework-ride (115)
- setnocounton (141)
- socket.gethostbyname (122)
- sqlmid (121)
- time.strptime (133)
- vscode格式化 (125)
- win32con (129)
- window.localstorage (126)