- js数字转化为千分位
- toLocaleString方法
const num=12345.6789
num.toLocaleString(); // "12,345.679"`
- 正则匹配
function format (num) {
return (num+ '').replace(/(\d{1,3})(?=(\d{3})+(?:$|.))/g,'$1,')
}
将秒转化为时分秒
function formatSeconds(value) {
let result = parseInt(value)
let h = Math.floor(result / 3600) < 10 ? '0' + Math.floor(result / 3600) : Math.floor(result / 3600);
let m = Math.floor((result / 60 % 60)) < 10 ? '0' + Math.floor((result / 60 % 60)) : Math.floor((result / 60 % 60));
let s = Math.floor((result % 60)) < 10 ? '0' + Math.floor((result % 60)) : Math.floor((result % 60));
let res = '';
if(h !== '00') res += `${h}h`;
if(m !== '00') res += `${m}min`;
res += `${s}s`;
return {h,m,s};
}
多层级对象合并
function assiginObj(target = {}, sources = {}) {
const obj = target
if (typeof target !== 'object' || typeof sources !== 'object') {
return sources // 如果其中一个不是对象 就返回sources
}
for (const key in sources) {
// 如果target也存在 那就再次合并
if (target.hasOwnProperty(key)) {
obj[key] = assiginObj(target[key], sources[key])
} else {
// 不存在就直接添加
obj[key] = sources[key]
}
}
return obj
}
本周起始日期
function getWeekDate() {
const now = new Date() // 当前日期
const nowDayOfWeek = now.getDay() // 今天本周的第几天
const nowDay = now.getDate() // 当前日
const nowMonth = now.getMonth() // 当前月
const nowYear = now.getFullYear() // 当前年
const weekStartDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek)
const weekEndDate = new Date(nowYear, nowMonth, nowDay + (6 - nowDayOfWeek))
const startTime = formatDate(weekStartDate) + ' 00:00:00'
const endTime = formatDate(weekEndDate) + ' 23:59:59'
return { startTime, endTime }
}