// 格式化日期类型,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); });
Empfohlenes Tutorial: „JS Tutorial“
Das obige ist der detaillierte Inhalt vonEine Reihe von Methoden, die häufig in der JavaScript-Entwicklung verwendet werden. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!