前端开发过程中,难以避免遇到重复类似的逻辑需要处理,遵循模块化,组件化的思路会提取出一部分高频次、高耦合的组件 用引入的方法让代码可读性更高更优雅。
同理在处理逻辑时也会遇到很多相似的场景,包括不限于格式化、请求等下面整理了一些常用方法的合集供大家参考。
// 深拷贝
const clone = (obj) => {
//处理三种简单类型/null/undefine
if (null == obj || "object" != typeof obj) return obj;
// 处理Date
if (obj instanceof Date) {
var copy = new Date();
copy.setTime(obj.getTime());
return copy;
}
// 处理Array
if (obj instanceof Array) {
var copy = [];
for (var i = 0; i < obj.length; ++i) {
copy[i] = clone(obj[i]);
}
return copy;
}
// 处理Object
if (obj instanceof Object) {
var copy = {};
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]);
}
return copy;
}
throw new Error("Unable to copy obj! Its type isn't supported.");
};
当然上述还有其他方法比如 return JSON.parse(JSON.stringify(obj)) 或者遍历的方法这里就不一一列举了
//截取请求中url携带的参数
const getQueryString = (name, str) => {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
str = str && str.substr(str.indexOf("?") + 1) || window.location.search.substr(1);
var r = str.match(reg);
if (r != null) return unescape(r[2]);
return null;
};
//截取参数并返回JSON
const parseUrl = () => {
var arr = location.search.split('?')[1].split('&');
var params = {};
for (var i = 0, l = arr.length; i < l; i++) {
var param = arr[i].split('=');
params[param[0]] = param[1];
}
return params;
};
//获取鼠标位置
const getMousePos = event => {
var e = event || window.event;
return {
'x': e.clientX,
'y': e.clientY
};
};
//日期时间格式化方法
const format = (type, value) => {
var a = '';
if (value == '' || value == null || value == undefined) {
return a;
} else {
if (typeof value == 'string' && value.indexOf('-') == -1) {
value = value.replace(/^(\d{4})(\d{2})(\d{2})$/, "$1-$2-$3");
}
switch (type) {
case 'YYYY-MM-DD':
var now = new Date(value);
var year = now.getFullYear();
var month = now.getMonth() + 1;
var month = month > 9 ? month : "0" + month;
var day = now.getDate() > 9 ? now.getDate() : "0" + now.getDate();
a = year + "-" + month + "-" + day;
break;
case 'YYYYMMDD':
var now = new Date(value);
var year = now.getFullYear();
var month = now.getMonth() + 1;
var month = month > 9 ? month : "0" + month;
var day = now.getDate() > 9 ? now.getDate() : "0" + now.getDate();
a = year.toString() + month.toString() + day.toString();
break;
case 'YYYY-MM':
var now = new Date(value);
var year = now.getFullYear();
var month = now.getMonth() + 1;
var month = month > 9 ? month : "0" + month;
a = year + "-" + month;
break;
case 'YYYYMM':
var now = new Date(value);
var year = now.getFullYear();
var month = now.getMonth() + 1;
var month = month > 9 ? month : "0" + month;
a = year + month;
break;
case 'YYYY-MM-DD-2':
var now = new Date(value.substring(0, 10));
var year = now.getFullYear();
var month = now.getMonth() + 1;
var month = month > 9 ? month : "0" + month;
var day = now.getDate() > 9 ? now.getDate() : "0" + now.getDate();
a = year + "-" + month + "-" + day;
break;
case 'YYYY.MM.DD':
var now = new Date(value);
var year = now.getFullYear();
var month = now.getMonth() + 1;
var month = month > 9 ? month : "0" + month;
var day = now.getDate() > 9 ? now.getDate() : "0" + now.getDate();
a = year + "." + month + "." + day;
break;
case 'MM月DD日hh:mm':
var now = new Date(value);
var month = now.getMonth() + 1;
var month = month > 9 ? month : "0" + month;
var day = now.getDate() > 9 ? now.getDate() : "0" + now.getDate();
var hours = now.getHours() > 9 ? now.getHours() : "0" + now.getHours();
var minutes = now.getMinutes() > 9 ? now.getMinutes() : "0" + now.getMinutes();
a = month + "月" + day + '日 ' + hours + ':' + minutes;
break;
case 'YYYY.MM.DD hh:mm':
var now = new Date(value);
var year = now.getFullYear();
var month = now.getMonth() + 1;
var month = month > 9 ? month : "0" + month;
var day = now.getDate() > 9 ? now.getDate() : "0" + now.getDate();
var hours = now.getHours() > 9 ? now.getHours() : "0" + now.getHours();
var minutes = now.getMinutes() > 9 ? now.getMinutes() : "0" + now.getMinutes();
a = year + "." + month + "." + day + '   ' + hours + ':' + minutes;
break;
case 'YYYY-MM-DD hh:mm:ss':
var now = new Date(value);
var year = now.getFullYear();
var month = now.getMonth() + 1;
var month = month > 9 ? month : "0" + month;
var day = now.getDate() > 9 ? now.getDate() : "0" + now.getDate();
var hours = now.getHours() > 9 ? now.getHours() : "0" + now.getHours();
var minutes = now.getMinutes() > 9 ? now.getMinutes() : "0" + now.getMinutes();
var seconds = now.getSeconds() > 9 ? now.getSeconds() : "0" + now.getSeconds();
a = year + "-" + month + "-" + day + ' ' + hours + ':' + minutes + ':' + seconds;
break;
case 'hh:mm':
var now = new Date(value);
var hours = now.getHours() > 9 ? now.getHours() : "0" + now.getHours();
var minutes = now.getMinutes() > 9 ? now.getMinutes() : "0" + now.getMinutes();
a = hours + ':' + minutes;
break;
case '00.00%':
a = (value * 100).toFixed(2).toString() + '%';
break;
case '00%':
a = (value * 100).toFixed(0).toString() + '%';
break;
case '00.00':
a = (value * 100).toFixed(2).toString();
break;
case 'html':
value = value.replace(/(\n)/g, "");
value = value.replace(/(\t)/g, "");
value = value.replace(/(\r)/g, "");
value = value.replace(/<\/?[^>]*>/g, "");
value = value.replace(/\s*/g, "");
a = value;
break;
}
}
return a;
};
//数组去重方法 该方法挂载在Array原型上
Array.prototype.unique = function () {
var res = [];
var json = {};
for (var i = 0; i < this.length; i++) {
if (!json[this[i]]) {
res.push(this[i]);
json[this[i]] = 1;
}
}
return res;
};
//千分位处理方法
const numWithDot = (str, length) => {
if (str < 0) {
var str_first = '-';
str = -str;
} else {
var str_first = '';
}
var str = '' + str;
var newStr = "";
var count = 0;
if (str.indexOf(".") == -1) {
for (var i = str.length - 1; i >= 0; i--) {
if (count % 3 == 0 && count != 0) {
newStr = str.charAt(i) + "," + newStr;
} else {
newStr = str.charAt(i) + newStr;
}
count++;
}
var dot = ''
if (length != 0) {
var oL = '';
for (var i = 0; i < length; i++) {
oL += '0';
}
dot = '.' + oL
}
//str = newStr + ".00"; //自动补小数点后两位
str = newStr + dot;
} else {
for (var i = str.indexOf(".") - 1; i >= 0; i--) {
if (count % 3 == 0 && count != 0) {
newStr = str.charAt(i) + "," + newStr;
} else {
newStr = str.charAt(i) + newStr; //逐个字符相接起来
}
count++;
}
var oL = '';
for (var i = 0; i < length; i++) {
oL += '0';
}
str = newStr + (str + oL).substr((str + oL).indexOf("."), length + 1);
}
return str_first + str;
};
//获取当月最后一天日期
const getLastDay = (year, month) => {
var new_year = year; //取当前的年份
var new_month = month++; //取下一个月的第一天,方便计算(最后一天不固定)
if (month > 12) //如果当前大于12月,则年份转到下一年
{
new_month -= 12; //月份减
new_year++; //年份增
}
var new_date = new Date(new_year, new_month, 1); //取当年当月中的第一天
return (new Date(new_date.getTime() - 1000 * 60 * 60 * 24)).getDate();
};
const downloadPost = (url, param, filename = "") => {
let isFail = null
fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
//"Authorization": token
},
body: JSON.stringify(param),
})
.then((res) => {
if (decodeURI(res.headers.get("Content-Type")).includes('application/json;')) {
isFail = true
return res.json();
} else {
isFail = false
try {
filename = decodeURI(res.headers.get("Content-Disposition").split("=")[1])
} catch (e) {
console.error("解析fileName错误");
}
return res.blob();
}
})
.then((data) => {
if (isFail) {
//报错
} else {
//创建a标签和临时地址 返回的data为文件
let blobUrl = window.URL.createObjectURL(data);
const a = document.createElement("a");
a.style.display = "none";
a.download = filename;
a.href = blobUrl;
a.click();
}
});
}
// 对已有的HTML代码中的a标签跳转额外弹窗
const aToBlank = (str) =>{
let aReg = /<a[^>]+href=[\\'"]([^'"]*)['"][\S|\s]*?>/g
let arr = str.match(aReg)
if(arr&&arr.length!=0){
arr.map(item=>{
let temp = item.slice(0,item.length-1) + ' target="_blank">'
str = str.replace(item,temp)
})
}
return str
}
// 对已有的HTML代码中的img标签设置100%宽度
const imgWidth = (str) =>{
let aReg = /<img[^>]+src=[\\'"]([^'"]*)['"][\S|\s]*?>/g
let arr = str.match(aReg)
if(arr&&arr.length!=0){
arr.map(item=>{
let temp = item.slice(0,item.length-1) + 'style="max-width:100%">'
str = str.replace(item,temp)
})
}
return str
}
更多方法持续更新中…