持续更新中...
封装方法传送门:
使用方法非常简单,只需放到你的 utils.js 工具文件中,直接 export const 加上我的封装方法,在别的文件中使用{方法1,方法2,方法3...}
引用后就可以直接使用了!
001.输入一个值,返回其数据类型
type = para => {
return Object.prototype.toString.call(para).slice(8,-1)
}
002.阶乘
factorial = num => {
if (num < 0) return -1
return num === 1 ? 1 : num * factorial(--num)
}
console.log(factorial(5))
003.两个数之间累乘
multBetride = (x, y) => {
let count;
if (x < y) {
count = x;
for (let i = x + 1; i <= y; i++) {
count *= i;
}
return count;
} else {
count = y;
for (let i = y + 1; i <= x; i++) {
count *= i;
}
return count;
}
}
004.累加
accuMulate = (...args) => {
return args.reduce((i, s) => { return i + s }, 0)
}
console.log(accuMulate(1,2,5,9))
005.计时器(计算代码块(函数)执行时间)
无参 computeTime(f)
computeTime = code => {
let startTime = new Date().getTime();
code();
let endTime = new Date().getTime();
let time = endTime - startTime;
return time;
}
有参 computeTime(f)
使用方法:computeTime(f,参数1,参数2......)
computeTime = f => {
let startTime = new Date().getTime();
let p = [];
for (let i = 1; i < arguments.length; i++) {
p.push(arguments[i])
}
f.apply(null, p)
let endTime = new Date().getTime();
let Time = endTime - startTime;
return Time;
}
006.数字超过9显示省略号
num_filter = val =>{
val = val?val-0:0;
if (val > 9 ) {
return "…"
}else{
return val;
}
}
007.数字超过99显示99+
ninenum_filter = val =>{
val = val?val-0:0;
if (val > 99 ) {
return "99+"
}else{
return val;
}
}
008.银行卡号分割
bank_filter = val =>{
val += '';
val = val.replace(/(\s)/g,'').replace(/(\d{4})/g,'$1 ').replace(/\s*$/,'');
return val;
}
009.防抖与节流
/**
* 函数防抖 (只执行最后一次点击)
*/
Debounce = (fn, t) => {
let delay = t || 500;
let timer;
return function () {
let args = arguments;
if(timer){
clearTimeout(timer);
}
timer = setTimeout(() => {
timer = null;
fn.apply(this, args);
}, delay);
}
};
/*
* 函数节流(一段时间内只执行一次)
*/
Throttle = (fn, t) => {
let last;
let timer;
let interval = t || 500;
return function () {
let args = arguments;
let now = +new Date();
if (last && now - last < interval) {
clearTimeout(timer);
timer = setTimeout(() => {
last = now;
fn.apply(this, args);
}, interval);
} else {
last = now;
fn.apply(this, args);
}
}
};
010.深拷贝
deepClone = source => {
const targetObj = source.constructor === Array ? [] : {}; // 判断复制的目标是数组还是对象
for (let keys in source) { // 遍历目标
if (source.hasOwnProperty(keys)) {
if (source[keys] && typeof source[keys] === 'object') { // 如果值是对象,就递归一下
targetObj[keys] = source[keys].constructor === Array ? [] : {};
targetObj[keys] = deepClone(source[keys]);
} else { // 如果不是,就直接赋值
targetObj[keys] = source[keys];
}
}
}
return targetObj;
}
let str1 = {
arr: [1, 2, 3],
obj: {
key: 'value'
},
fn: function () {
return 1;
}
};
let str3 = deepClone(str1);
console.log(str3 === str1); // false
console.log(str3.obj === str1.obj); // false
console.log(str3.fn === str1.fn); // true
011.获取视口尺寸
需要在HTML文件中运行
function getViewportOffset() {
if (window.innerWidth) {
return {
w: window.innerWidth,
h: window.innerHeight
}
} else {
// ie8及其以下
if (document.compatMode === "BackCompat") {
// 怪异模式
return {
w: document.body.clientWidth,
h: document.body.clientHeight
}
} else {
// 标准模式
return {
w: document.documentElement.clientWidth,
h: document.documentElement.clientHeight
}
}
}
}
012.数字前补零
/**
* num为你想要进行填充的数字
* length为你想要的数字长度
*/
//迭代方式实现
padding1=(num, length)=> {
for(let len = (num + "").length; len < length; len = num.length) {
num = "0" + num;
}
return num;
}
//递归方式实现
padding2=(num, length) =>{
if((num + "").length >= length) {
return num;
}
return padding2("0" + num, length)
}
//转为小数
padding3=(num, length)=> {
let decimal = num / Math.pow(10, length);
//toFixed指定保留几位小数
decimal = decimal.toFixed(length) + "";
return decimal.substr(decimal.indexOf(".")+1);
}
//填充截取法
padding4=(num, length)=> {
//这里用slice和substr均可
return (Array(length).join("0") + num).slice(-length);
}
//填充截取法
padding5=(num, length)=> {
let len = (num + "").length;
let diff = length+1 - len;
if(diff > 0) {
return Array(diff).join("0") + num;
}
return num;
}
013.格式转换:base64转file
/**
* base64 base64
* filename 转换后的文件名
*/
base64ToFile = (base64, filename )=> {
let arr = base64.split(',')
let mime = arr[0].match(/:(.*?);/)[1]
let suffix = mime.split('/')[1] // 图片后缀
let bstr = atob(arr[1])
let n = bstr.length
let u8arr = new Uint8Array(n)
while (n--) {
u8arr[n] = bstr.charCodeAt(n)
}
return new File([u8arr], `${filename}.${suffix}`, { type: mime })
}
014.格式转换:base64转blob
base64ToBlob = base64 => {
let arr = base64.split(','),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
n = bstr.length,
u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], { type: mime });
};
015.格式转换:blob转file
blobToFile = (blob, fileName) => {
blob.lastModifiedDate = new Date();
blob.name = fileName;
return blob;
};
016.格式转换:file转base64
/**
* file 图片文件
* 返回图片的Base64数据
*/
fileToBase64 = file => {
let reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function (e) {
return e.target.result
};
}
017.获取地址栏传递过来的参数
不是hash地址(地址栏没有#)
/**
* name为地址栏传递过来的字段名
*/
getQueryString = name => {
let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
let r = window.location.search.substr(1).match(reg);
if (r != null) return unescape(r[2]); return null;
}
// 测试
// http://localhost:3306/admin?id=111&name=xxx
// console.log(getQueryString('id')); // 111
// console.log(getQueryString('name')); // xxx
hash地址(地址栏有#)
getQueryString (val) {
const w = location.hash.indexOf('?')
const query = location.hash.substring(w + 1)
const arr = query.split('&')
for (let i = 0; i < arr.length; i++) {
const pair = arr[i].split('=')
if (pair[0] == val) { return pair[1] }
}
return null
}
018.对象处理为数组对象
/**
* obj 需要处理的对象
*/
objToArrObj = obj => {
let arr = []
for(let i in obj){
arr.push({[i]:obj[i]})
}
return arr
}
// 测试数据
let obj = {20180410: 5, 20180411: 13, 20180412: 26, 20180413: 16}
console.log(objToArrObj(obj));
/*
[
{ 20180410: 5 },
{ 20180411: 13 },
{ 20180412: 26 },
{ 20180413: 16 }
]
*/
019.对象序列化为querystring的形式
/**
* 将对象序列化为querystring的形式
* 每个字段的值都会经过url编码
* @param data
* @returns {string}
*/
getParamStrFromObj = (data = {}, paramProxy = '') => Object.keys(data)
.map(key => {
if (paramProxy) {
return `${paramProxy}[${key}]=${encodeURIComponent(data[key])}`
}
return `${key}=${encodeURIComponent(data[key])}`
})
.join('&')
020.对象序列化为querystring的形式
/**
* 将对象序列化为querystring的形式
* 特殊字符不需要转的情况使用
* @param data
* @returns {string}
*/
getParamStrFromObjDecode = (data = {}, paramProxy = '') => Object.keys(data)
.map(key => {
if (paramProxy) {
return `${paramProxy}[${key}]=${data[key]}`
}
return `${key}=${data[key]}`
})
.join('&')
021.判断对象的val是不是为空
/**
* 判断对象的val是不是为空
* @param {Object} obj 要校验的对象
* @param {Array} keyArr 不需要校验的key集合
* @param {Function} func 校验为空时要执行的回调
* @param {Function} successFn 检验不为空时要执行的回调
*/
objValueIsNull = (obj, keyArr, func, successFn) => {
// 返回二维数组 index:0对应key index:1对应val
let objArr = Object.entries(obj)
let objArrItem = objArr.reduce((preVal, cur, index) =>
keyArr.includes(cur[0]) || preVal[1] === '' ? preVal : (cur[1] !== '' ? [''] : cur), [])
if (objArrItem[0]) {
func && func(objArrItem[0])
return
}
successFn && successFn()
}
022.JSON格式验证
isJSON = (s) => {
try {
let obj = JSON.parse(s)
return typeof obj === 'object' && obj !== null
} catch (e) {
return false
}
}
023.base64格式验证
isBase64 = (s) => {
return /data:image\/.+;base64,/.test(s)
}
024.复制内容
/**
* 复制内容
* @param {String} content 要复制的内容 此函数不能直接跟在异步函数之后 若跟在异步函数后可能会有兼容问题)
* @return {boolean}
*/
copyContent = content => {
if (!content) {
return false
}
const input = document.createElement('input')
input.value = content
input.style.position = 'absolute'
document.documentElement.appendChild(input)
input.select()
document.execCommand('copy')
document.documentElement.removeChild(input)
return true
}
025.获取字符串的中文全角长度
getStrByte = str => {
if (typeof str !== 'string' || str.length === 0) {
return 0
}
const doubleChar = str.match(/[^\u0000-\u00ff]/g)
const doubleCharLen = doubleChar ? doubleChar.length : 0
return doubleCharLen
}
026.下划线转驼峰
toHump = str => {
return str.replace(/_(\w)/g, (_, l) => {
return l.toUpperCase();
});
}
027.驼峰转下划线
toLine = str => {
return str.replace(/([A-Z])/g,"_$1").toLowerCase();
}
028.统计字符串或数组中出现字符的次数
strArrNum = para => {
let arr = []
para instanceof Array
? arr = para
: arr = para.split('')
return arr.reduce((p, v) => {
if (p[v]) {
p[v] += 1
} else {
p[v] = 1
}
return p
}, {})
}
029.通过base64获取照片存储大小(返回字节)
getBase64Size = base64 = {
if (base64) {
base64=base64.split(",")[1].split("=")[0];
let strLength = base64.length;
let fileLength = strLength - (strLength / 8) * 2;
return Math.floor(fileLength);
} else {
return null
}
},
030.转义标签(预防XSS攻击)
var encodeHtml = function (str) {\
return (str + '').replace(/&/g, '&')\
.replace(/</g, '<')\
.replace(/>/g, '>')\
.replace(/\x60/g, '`')\
.replace(/\x27/g, ''')\
.replace(/\x22/g, '"');\
}
031.将字符串中的实体转换为原字符
var decodeHtml = function (str) {\
return (str + '').replace(/"/g, '\x22')\
.replace(/�*39;/g, '\x27')\
.replace(/�*96;/g, '\x60')\
.replace(/>/g, '>')\
.replace(/</g, '<')\
.replace(/&/g, '&');\
}
032. 从URL中获取指定的参数值
getUrlParam: function (key, str) {
if (!str) {
str = document.location.toString().replace(/#.*$/g, '');
}
var reg = new RegExp("(^|&|\\\\?)" + key + "=([^&]*)(&|$|#)"),
r = str.match(reg);
if (r) {
return r[2];
}
return "";
}