引言
在前端开发中,JavaScript是必不可少的一部分,而掌握各种常用的公共方法更是提升开发效率和代码质量的关键。无论你是初学者还是资深开发者,了解并熟练运用这些方法都能让你的代码更加简洁、高效。本篇博客将为你详细汇总并解析最全的JavaScript公共方法,涵盖数组、对象、字符串、日期等各个方面的常用技巧。希望通过这篇文章,能为你的前端开发之路提供有力的帮助,成为你开发过程中不可或缺的参考指南。
下面开始啦,建议收藏起来,前端开发项目必备。
1 安装js-tool-big-box工具包
1.1 安装
我已经将所有公共方法,按模块的形式,集成到了js-tool-big-box工具包中,大家不比担心安装后会使项目体积变大,不会的。
执行安装命令:
npm i js-tool-big-box
npm包地址:js-tool-big-box - npm (npmjs.com) 包中提供了工具的学习文档地址以及作者
1.2 截至目前的方法集合
那么js-tool-big-box这个方法库现在都有哪些公共方法可以供大家使用了呢,我们看一下下面的图就知道啦
2 时间日期类
想要使用时间日期类的公共方法,需要先在项目中导入 timeBox 对象,所有的时间日期类方法都在这个对象下面,引入代码如下:
import {
timeBox } from 'js-tool-big-box';
2.1 更灵活的年月日时分秒
const year = timeBox.getMyYear(null, '年');
console.log(year); // 2024年
const yearALB = timeBox.getMyYear(null, 'سنة');
console.log(yearALB); // 2024سنة
const month = timeBox.getMyMonth(null, '月');
console.log(month); // 05月
const date = timeBox.getMyDate(null);
console.log(date); // 23
const hour = timeBox.getMyHour(null, 'hour');
console.log(hour); // 20hour
const minutes = timeBox.getMyMinutes(null, 'min');
console.log(minutes); // 10min
const seconds = timeBox.getMySeconds(null, '秒');
console.log(seconds); // 10秒
2.2 日期时间转换
const dateTime1 = timeBox.getFullDateTime(null, 'YYYY-MM-DD', '/');
console.log(dateTime1); // 2024/05/22
const dateTime2 = timeBox.getFullDateTime(null, 'YYYY-MM-DD hh:mm', '~');
console.log(dateTime2); // 2024`05`22 20:11
const dateTime3 = timeBox.getFullDateTime(null, 'YYYY-MM-DD hh:mm:ss');
console.log(dateTime3); // 2024-05-22 20:11:22
2.3 个性的时间组合
const hourShow= timeBox.getMyDate(null, '点');
const minShow= timeBox.getMyMinutes(null, '分');
const timeShow = `${
hourShow} ${
minShow}`; // 8点 22分
2.4 某个时间距离现在
const unitObj = {
beforeUnit: 'before',
afterUnit: 'after',
yearUnit: 'year',
monthUnit: 'month',
dateUnit: ' days ',
hourUnit: 'hour',
minutesUnit: 'min',
secondUnit: 'sec'
}
const showData = timeBox.getDistanceNow('1908-12-02 06:00:00', unitObj); // 溥仪登基啦
console.log('溥仪登基详细时间===', showData);
const showData1 = timeBox.getDistanceNow('2030-04-19 20:15:59'); // 移民火星啦
console.log('人类移民火星详细时间===', showData1);
注意:这个方法返回的是详细的时间对象,需要甄别使用哪个具体的详细信息。
2.5 平年还是闰年
const leapYear = timeBox.getLeapYear('2024-12');
console.log('=-=2024年是', leapYear ? '闰年': '平年'); // 闰年
const leapYear1 = timeBox.getLeapYear('2019');
console.log('=-=2019年是', leapYear1 ? '闰年': '平年'); // 平年
const leapYear2 = timeBox.getLeapYear(null);
console.log('=-=今年是', leapYear2 ? '闰年': '平年'); // 闰年
2.6 指定月份的天数
const days = timeBox.getDaysInMonth('2023', 11);
console.log(