js常用的一些工具类
//截取路径参数
function getParams(key) {
var reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg);
if (r != null) {
return unescape(r[2]);
}
return null;
};
//数组拆分
function handlerDatas(arr) {
let obj = {};
arr.forEach((item, index) => {
let {部件名称} = item;
if (!obj[部件名称]) {
obj[部件名称] = {
部件名称,
children: []
}
}
obj[部件名称].children.push(item);
});
let data = Object.values(obj); // 最终输出
return data;
}
//数组去重
function uniqueArray(array, key) {
var result = [array[0]];
for (var i = 1; i < array.length; i++) {
var item = array[i];
var repeat = false;
for (var j = 0; j < result.length; j++) {
if (item[key] == result[j][key]) {
repeat = true;
break;
}
}
if (!repeat) {
result.push(item);
}
}
return result;
}
//日期转字符串格式
function DateToStr(date) {
var year = date.getFullYear();//年
var month = date.getMonth();//月
var day = date.getDate();//日
var hours = date.getHours();//时
var min = date.getMinutes();//分
var second = date.getSeconds();//秒
return year + "-" +
((month + 1) > 9 ? (month + 1) : "0" + (month + 1)) + "-" +
(day > 9 ? day : ("0" + day)) + " " +
(hours > 9 ? hours : ("0" + hours)) + ":" +
(min > 9 ? min : ("0" + min)) + ":" +
(second > 9 ? second : ("0" + second));
}
//字符串转日期
function StrToDate(datestr) {
return new Date(datestr);
}
//计算两个日期相差天数
function DateDiff(sDate1, sDate2) {
//sDate1和sDate2是2006-12-18格式
var aDate, oDate1, oDate2, iDays;
aDate = sDate1.split("-");
oDate1 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0]);
aDate = sDate2.split("-");
oDate2 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0]);
iDays = parseInt(Math.abs(oDate1 - oDate2) / 1000 / 60 / 60 / 24);//把相差的毫秒数转换为天数
return iDays;
}
//获得两个日期间所有日期-fn1
Date.prototype.format = function () {
var s = '';
var mouth = (this.getMonth() + 1) >= 10 ? (this.getMonth() + 1) : ('0' + (this.getMonth() + 1));
var day = this.getDate() >= 10 ? this.getDate() : ('0' + this.getDate());
s += this.getFullYear() + '-'; // 获取年份。
s += mouth + "-"; // 获取月份。
s += day; //获取日。
return (s); //返回日期。
};
//获得两个日期间所有日期-fn2
function getAll(begin, end) {
var return_ = [];
var ab = begin.split("-");
var ae = end.split("-");
var db = new Date();
db.setUTCFullYear(ab[0], ab[1] - 1, ab[2]);
var de = new Date();
de.setUTCFullYear(ae[0], ae[1] - 1, ae[2]);
var unixDb = db.getTime();
var unixDe = de.getTime();
for (var k = unixDb; k <= unixDe;) {
return_.push((new Date(parseInt(k))).format());
k = k + 24 * 60 * 60 * 1000;
}
return return_;
}
//日期加减
function dateOperator(date, days, operator) {
date = date.replace(/-/g, "/"); //更改日期格式
var nd = new Date(date);
nd = nd.valueOf();
if (operator == "+") {
nd = nd + days * 24 * 60 * 60 * 1000;
} else if (operator == "-") {
nd = nd - days * 24 * 60 * 60 * 1000;
} else {
return false;
}
nd = new Date(nd);
var y = nd.getFullYear();
var m = nd.getMonth() + 1;
var d = nd.getDate();
if (m <= 9) m = "0" + m;
if (d <= 9) d = "0" + d;
var cdate = y + "-" + m + "-" + d;
return cdate;
}