269个JavaScript工具函数,助你提升工作效率(5)
作者:互联网
121.cookie 获取
/**
* @param {String} key 属性
*/
export const cookieGet = (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
};
122.cookie 删除
/**
* @param {String} key 属性
*/
export const cookieRemove = (key) => {
document.cookie = `${encodeURIComponent(key)}=;expires=${new Date()}`
};
123.更多的工具函数
这里包含了平时可能常用的工具函数,包含数字,字符串,数组和对象等等操作。
124.金钱格式化,三位加逗号
/**
* @param { number } num
*/
export const formatMoney = num => num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
125.截取字符串并加身略号
export function subText(str, length) {
if (str.length === 0) {
return '';
}
if (str.length > length) {
return str.substr(0, length) + "...";
} else {
return str;
}
}
126.获取文件base64编码
/**
* @param file
* @param format 指定文件格式
* @param size 指定文件大小(字节)
* @param formatMsg 格式错误提示
* @param sizeMsg 大小超出限制提示
* @returns {Promise<any>}
*/
export function fileToBase64String(file, format = ['jpg', 'jpeg', 'png', 'gif'], size = 20 * 1024 * 1024, formatMsg = '文件格式不正确', sizeMsg = '文件大小超出限制') {
return new Promise((resolve, reject) => {
// 格式过滤
let suffix = file.type.split('/')[1].toLowerCase();
let inFormat = false;
for (let i = 0; i < format.length; i++) {
if (suffix === format[i]) {
inFormat = true;
break;
}
}
if (!inFormat) {
reject(formatMsg);
}
// 大小过滤
if (file.size > size) {
reject(sizeMsg);
}
// 转base64字符串
let fileReader = new FileReader();
fileReader.readAsDataURL(file);
fileReader.onload = () => {
let res = fileReader.result;
resolve({base64String: res, suffix: suffix});
reject('异常文件,请重新选择');
}
})
}
127.B转换到KB,MB,GB并保留两位小数
/**
* @param { number } fileSize
*/
export function formatFileSize(fileSize) {
let temp;
if (fileSize < 1024) {
return fileSize + 'B';
} else if (fileSize < (1024 * 1024)) {
temp = fileSize / 1024;
temp = temp.toFixed(2);
return temp + 'KB';
} else if (fileSize < (1024 * 1024 * 1024)) {
temp = fileSize / (1024 * 1024);
temp = temp.toFixed(2);
return temp + 'MB';
} else {
temp = fileSize / (1024 * 1024 * 1024);
temp = temp.toFixed(2);
return temp + 'GB';
}
}
128.base64转file
/**
* @param { base64 } base64
* @param { string } filename 转换后的文件名
*/
export const 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 })
};
129.base64转blob
/**
* @param { base64 } base64
*/
export const 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 });
};
130.blob转file
/**
* @param { blob } blob
* @param { string } fileName
*/
export const blobToFile = (blob, fileName) => {
blob.lastModifiedDate = new Date();
blob.name = fileName;
return blob;
};
131.file转base64
/**
* @param { * } file 图片文件
*/
export const fileToBase64 = file => {
let reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function (e) {
return e.target.result
};
};
132.递归生成树形结构
export function getTreeData(data, pid, pidName = 'parentId', idName = 'id', childrenName = 'children', key) {
let arr = [];
for (let i = 0; i < data.length; i++) {
if (data[i][pidName] == pid) {
data[i].key = data[i][idName];
data[i][childrenName] = getTreeData(data, data[i][idName], pidName, idName, childrenName);
arr.push(data[i]);
}
}
return arr;
}
133.遍历树节点
export function foreachTree(data, childrenName = 'children', callback) {
for (let i = 0; i < data.length; i++) {
callback(data[i]);
if (data[i][childrenName] && data[i][childrenName].length > 0) {
foreachTree(data[i][childrenName], childrenName, callback);
}
}
}
134.追溯父节点
export function traceParentNode(pid, data, rootPid, pidName = 'parentId', idName = 'id', childrenName = 'children') {
let arr = [];
foreachTree(data, childrenName, (node) => {
if (node[idName] == pid) {
arr.push(node);
if (node[pidName] != rootPid) {
arr = arr.concat(traceParentNode(node[pidName], data, rootPid, pidName, idName));
}
}
});
return arr;
}
135.寻找所有子节点
export function traceChildNode(id, data, pidName = 'parentId', idName = 'id', childrenName = 'children') {
let arr = [];
foreachTree(data, childrenName, (node) => {
if (node[pidName] == id) {
arr.push(node);
arr = arr.concat(traceChildNode(node[idName], data, pidName, idName, childrenName));
}
});
return arr;
}
136.根据pid生成树形结构
/**
* @param { object } items 后台获取的数据
* @param { * } id 数据中的id
* @param { * } link 生成树形结构的依据
*/
export const createTree = (items, id = null, link = 'pid') =>{
items.filter(item => item[link] === id).map(item => ({ ...item, children: createTree(items, item.id) }));
};
137.查询数组中是否存在某个元素并返回元素第一次出现的下标
/**
* @param {*} item
* @param { array } data
*/
export function inArray(item, data) {
for (let i = 0; i < data.length; i++) {
if (item === data[i]) {
return i;
}
}
return -1;
}
138.Windows根据详细版本号判断当前系统名称
/**
* @param { string } osVersion
*/
export function OutOsName(osVersion) {
if(!osVersion){
return
}
let str = osVersion.substr(0, 3);
if (str === "5.0") {
return "Win 2000"
} else if (str === "5.1") {
return "Win XP"
} else if (str === "5.2") {
return "Win XP64"
} else if (str === "6.0") {
return "Win Vista"
} else if (str === "6.1") {
return "Win 7"
} else if (str === "6.2") {
return "Win 8"
} else if (str === "6.3") {
return "Win 8.1"
} else if (str === "10.") {
return "Win 10"
} else {
return "Win"
}
}
139.判断手机是Andoird还是IOS
/**
* 0: ios
* 1: android
* 2: 其它
*/
export function 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 0;
}
if (isAndroid) {
return 1;
}
return 2;
}
140.函数防抖
/**
* @param { function } func
* @param { number } wait 延迟执行毫秒数
* @param { boolean } immediate true 表立即执行,false 表非立即执行
*/
export function debounce(func,wait,immediate) {
let timeout;
return function () {
let context = this;
let args = arguments;
if (timeout) clearTimeout(timeout);
if (immediate) {
let callNow = !timeout;
timeout = setTimeout(() => {
timeout = null;
}, wait);
if (callNow) func.apply(context, args)
}
else {
timeout = setTimeout(() => {
func.apply(context, args)
}, wait);
}
}
}
145.函数节流
/**
* @param { function } func 函数
* @param { number } wait 延迟执行毫秒数
* @param { number } type 1 表时间戳版,2 表定时器版
*/
export function throttle(func, wait ,type) {
let previous, timeout;
if(type===1){
previous = 0;
}else if(type===2){
timeout = null;
}
return function() {
let context = this;
let args = arguments;
if(type===1){
let now = Date.now();
if (now - previous > wait) {
func.apply(context, args);
previous = now;
}
}else if(type===2){
if (!timeout) {
timeout = setTimeout(() => {
timeout = null;
func.apply(context, args)
}, wait)
}
}
}
}
146.判断数据类型
/**
* @param {*} target
*/
export function type(target) {
let ret = typeof(target);
let template = {
"[object Array]": "array",
"[object Object]":"object",
"[object Number]":"number - object",
"[object Boolean]":"boolean - object",
"[object String]":'string-object'
};
if(target === null) {
return 'null';
}else if(ret == "object"){
let str = Object.prototype.toString.call(target);
return template[str];
}else{
return ret;
}
}
147.生成指定范围随机数
/**
* @param { number } min
* @param { number } max
*/
export const RandomNum = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
148.数组乱序
/**
* @param {array} arr
*/
export function arrScrambling(arr) {
let array = arr;
let index = array.length;
while (index) {
index -= 1;
let randomIndex = Math.floor(Math.random() * index);
let middleware = array[index];
array[index] = array[randomIndex];
array[randomIndex] = middleware
}
return array
}
150.数组交集
/**
* @param { array} arr1
* @param { array } arr2
*/
export const similarity = (arr1, arr2) => arr1.filter(v => arr2.includes(v));
标签:arr,return,JavaScript,param,工作效率,let,export,269,data 来源: https://www.cnblogs.com/czf1987/p/14636536.html