JavaScript 常用方法:JS日期格式化函数、JS实现并列排序、JS实现数字每三位添加逗号、JS 实现根据日期和时间进行排序
warning:
这篇文章距离上次修改已过189天,其中的内容可能已经有所变动。
// JS日期格式化函数
function formatDate(date, format) {
const map = {
'M': date.getMonth() + 1, // 月份
'd': date.getDate(), // 日
'h': date.getHours(), // 小时
'm': date.getMinutes(), // 分钟
's': date.getSeconds(), // 秒
};
format = format.replace(/(M+|d+|h+|m+|s+)/g, function(all) {
return ('0' + map[all.charAt(0)]).slice(-2);
});
return format;
}
// 使用示例
const now = new Date();
console.log(formatDate(now, 'yyyy-MM-dd hh:mm:ss')); // 输出格式化的日期字符串
// JS实现并列排序函数
function sortBy(arr, prop, desc = false) {
const compare = (a, b) => {
if (a[prop] < b[prop]) return desc ? 1 : -1;
if (a[prop] > b[prop]) return desc ? -1 : 1;
return 0;
};
return arr.sort(compare);
}
// 使用示例
const users = [{ name: 'Bob', age: 25 }, { name: 'Alice', age: 30 }, { name: 'Dave', age: 25 }];
console.log(sortBy(users, 'name')); // 按name属性升序排序
console.log(sortBy(users, 'age', true)); // 按age属性降序排序
// JS实现数字每三位添逗号函数
function addCommas(num) {
const numStr = num.toString();
return numStr.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
// 使用示例
console.log(addCommas(1234567)); // 输出: 1,234,567
以上代码提供了日期格式化、数组对象属性并列排序以及数字每三位添逗号的功能,并给出了使用示例。这些是JavaScript中常用的功能,对于开发者来说,可以直接复用在项目中,提高开发效率。
评论已关闭