以下文章来源于前端充电宝 ,作者CUGGZ
一.数字操作
1: 生成指定范围随机数
export const randomNum = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
2: 数字千位分割
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;
}
}
}
二.数组操作
1: 数组乱序
export const arrScrambling = (arr) => {
for (let i = 0; i < arr.length; i++) {
const randomIndex = Math.round(Math.random() * (arr.length - 1 - i)) + i;
[arr[i], arr[randomIndex]] = [arr[randomIndex], arr[i]];
}
return arr;
}
2: 数组扁平化
export const flatten = (arr) => {
let result = [];
for(let i = 0; i < arr.length; i++) {
if(Array.isArray(arr[i])) {
result = result.concat(flatten(arr[i]));
} else {
result.push(arr[i]);
}
}
return result;
}
3: 数组中获取随机数
export const sample = arr => arr[Math.floor(Math.random() * arr.length)];
三.字符串操作
1: 生成随机字符串
export const randomString = (len) => {
let chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz123456789';
let strLen = chars.length;
let randomStr = '';
for (let i = 0; i < len; i++) {
randomStr += chars.charAt(Math.floor(Math.random() * strLen));
}
return randomStr;
};
2: 字符串首字母大写
export const fistLetterUpper = (str) => {
return str.charAt(0).toUpperCase() + str.slice(1);
};
3: 手机号中间四位变成*
export const telFormat = (tel) => {
tel = String(tel);
return tel.substr(0,3) + "****" + tel.substr(7);
};
四.格式转化
1: 数字转化为大写金额
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(/^整$/, '零元整');
};
2: 数字转化为中文数字
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]]
}
}
});
}
五.操作存储
1: 存储loalStorage
export const loalStorageSet = (key, value) => {
if (!key) return;
if (typeof value !== 'string') {
value = JSON.stringify(value);
}
window.localStorage.setItem(key, value);
};
2: 获取loalStorage
export const loalStorageGet = (key) => {
if (!key) return;
return window.localStorage.getItem(key);
};
3: 删除localStorage
export const loalStorageRemove = (key) => {
if (!key) return;
window.localStorage.removeItem(key);
};
4: 存储sessionStorage
export const sessionStorageSet = (key, value) => {
if (!key) return;
if (typeof value !== 'string') {
value = JSON.stringify(value);
}
window.sessionStorage.setItem(key, value)
};
5: 获取sessionStorage
export const sessionStorageGet = (key) => {
if (!key) return;
return window.sessionStorage.getItem(key)
};
6: 删除sessionStorage
export const sessionStorageRemove = (key) => {
if (!key) return;
window.sessionStorage.removeItem(key)
};
六.操作cookie
1: 设置cookie
export const setCookie = (key, value, expire) => {
const d = new Date();
d.setDate(d.getDate() + expire);
document.cookie = `${key}=${value};expires=${d.toUTCString()}`
};
2: 读取cookie
export const getCookie = (key) => {
const cookieStr = unescape(document.cookie);
const arr = cookieStr.split('; ');
let cookieValue = '';
for (let i = 0; i < arr.length; i++) {
const temp = arr[i].split('=');
if (temp[0] === key) {
cookieValue = temp[1];
break
}
}
return cookieValue
};
3: 删除cookie
export const delCookie = (key) => {
document.cookie = `${encodeURIComponent(key)}=;expires=${new Date()}`
};
七.浏览器操作
1:滚动到页面顶部
export const scrollToTop = () => {
const height = document.documentElement.scrollTop || document.body.scrollTop;
if (height > 0) {
window.requestAnimationFrame(scrollToTop);
window.scrollTo(0, height - height / 8);
}
}
2:滚动到页面底部
export const scrollToBottom = () => {
window.scrollTo(0, document.documentElement.clientHeight);
}
3:滚动到指定元素区域
export const smoothScroll = (element) => {
document.querySelector(element).scrollIntoView({
behavior: 'smooth'
});
};
4:获取可视窗口高度
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;
}
5:获取可视窗口宽度
export const getPageViewWidth = () => {
return (document.compatMode == "BackCompat" ? document.body : document.documentElement).clientWidth;
}
6:打开浏览器全屏
export const toFullScreen = () => {
let element = document.body;
if (element.requestFullscreen) {
element.requestFullscreen()
} else if (element.mozRequestFullScreen) {
element.mozRequestFullScreen()
} else if (element.msRequestFullscreen) {
element.msRequestFullscreen()
} else if (element.webkitRequestFullscreen) {
element.webkitRequestFullScreen()
}
}
7:退出浏览器全屏
export const exitFullscreen = () => {
if (document.exitFullscreen) {
document.exitFullscreen()
} else if (document.msExitFullscreen) {
document.msExitFullscreen()
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen()
} else if (document.webkitExitFullscreen) {
document.webkitExitFullscreen()
}
}