日期格式化
// 格式化日期類型,fmt格式可選擇
function dateFormat(fmt, date) {
let ret;
let opt = {
"Y+": date.getFullYear().toString(), // 年
"M+": (date.getMonth() + 1).toString(), // 月
"D+": date.getDate().toString(), // 日
"h+": date.getHours().toString(), // 時
"m+": date.getMinutes().toString(), // 分
"s+": date.getSeconds().toString(), // 秒
"ms+": date.getMilliseconds().toString() // 毫秒
};
for (let k in opt) {
ret = new RegExp("(" + k + ")").exec(fmt);
if (ret) {
fmt = fmt.replace(ret[1], ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, "0"));
}
}
return fmt;
}
let date = new Date();
let fDate = dateFormat("YYYY-MM-DD hh:mm:ss.ms", new Date(date));
計算時分秒差值
// 計算時分秒差值
function timeDiffer(beginTime, endTime) {
let ret = {};
let date = new Date();
let sTime = Date.parse(dateFormat("YYYY/MM/DD", date) + " " + beginTime);
if (beginTime >= endTime) {
date.setDate(date.getDate() + 1);
}
let eTime = Date.parse(dateFormat("YYYY/MM/DD", date) + " " + endTime);
let differ = eTime - sTime;
let hour = Math.floor(differ / 1000 / 60 / 60);
let minute = Math.floor(differ / 1000 / 60 - hour * 60);
let second = Math.floor(differ / 1000 - hour * 60 * 60);
ret = {
differHour: hour,
differMinute: minute,
differSecond: second
};
return ret;
}
let { differHour, differMinute, differSecond } = timeDiffer(beginTime, endTime);
深拷貝
// 深拷貝,即複製並獨立一份數據,操做不影響原數據
function deepCopy(obj) {
if (typeof obj !== "object") {
return obj;
}
let result = Array.isArray(obj) ? [] : {};
for (let i in obj) {
if (obj.hasOwnProperty(i)) {
if (typeof obj[i] === "object" && obj[i] !== null) {
result[i] = deepCopy(obj[i]);
} else {
result[i] = obj[i];
}
}
}
return result;
}
數組去重
// ES6最簡方法
let result = [];
if (Array.isArray(arr)) {
result = new Set(arr);
}
// 數組去重
function unique(arr) {
if (!Array.isArray(arr)) {
return;
}
let result = [];
for (let i = 0; i < arr.length; i++) {
if (result.indexOf(arr[i]) === -1) {
result.push(arr[i]);
}
}
return result;
}
數組對象排序
// 數組對象排序,比較兩個字符串
list.sort((a, b) => {
return a.id.localeCompare(b.id);
});