在日常开发中经常有一些小问题需要解决,如果直接去找相应的工具包会比较费时间,为此在今天的文章中,我分享一些有用的JavaScript代码,学会使用这些代码可以快速提升开发效率,希望对你有用。大家可以借鉴下面的思路在自己的JavaScript项目中封装自己的工具类完成功能需求。
1、date相关
const date = new Date();
// 返回当前年
const getYear = () => date.getFullYear();
// 返回当前月
const getMonth = () => date.getMonth() + 1;
// 返回当前日
const getDay = () => date.getDate();
// 返回当前时
const getHour = () => date.getHours();
// 返回当前分
const getMinute = () => date.getMinutes();
// 返回当前秒
const getSecond = () => date.getSeconds();
// 返回类如yyyy-MM-dd的形式的当前日期
let getDate = function () {
let month = getMonth() < 10 ? "0" + getMonth() : getMonth();
let day = getDay() < 10 ? "0" + getDay() : getDay();
return getYear() + "-" + month + "-" + day;
};
console.log(getDate());
// 返回类如2022-06-24 16:56:45的日期时间字符串
const getCurrentTime = function () {
let hour = getHour() < 10 ? "0" + getHour() : getHour();
let minute = getMinute() < 10 ? "0" + getMinute() : getMinute();
let second = getSecond() < 10 ? "0" + getSecond() : getSecond();
return getDate() + " " + hour + ":" + minute + ":" + second;
};
console.log(getCurrentTime());
2、number相关
// 这里面封装了跟number相关的一些工具代码
// 检查一个数字是否为偶数
const isEven = (number) => number % 2 === 0;
console.log(isEven(8)) // true
console.log(isEven(13)) // false
// 检查一个数字是否为奇数
const isOdd = (number) => number % 2 !== 0;
console.log(isOdd(8)) // false
console.log(isOdd(13)) // true
// 随机生成整数: 基于两个参数生成一个随机整数
const randomInteger = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
console.log(randomInteger(1, 10)) // 随机生成一个1到10的整数
// 随机整数: 根据当前时间生成一个随机整数
const randomIntegerByDateTime = () => new Date().getTime();
console.log(randomIntegerByDateTime()); // 生成当前时间的毫秒数当随机数
// 将数字转换为小写字母(这里的根据是ASCII码)
const numberToLowerLetter = (value) => String.fromCharCode(96 + value);
console.log(numberToLowerLetter(1)); // a
// 将数字转换为大写字母(这里的根据是ASCII码)
const numberToUpperLetter = (value) => String.fromCharCode(64 + value);
console.log(numberToUpperLetter(1)); // A
3、boolean相关
// 这里面封装了跟boolean相关的一些工具代码
// 生成随机布尔值
const randomBoolean = () => Math.random() >= 0.5;
console.log(randomBoolean());
console.log(randomBoolean());
console.log(randomBoolean());
// 切换布尔值,变假为真,变真为假
const toggleBoolean = (val) => (val = !val);
console.log(toggleBoolean(true));
console.log(toggleBoolean(false));
4、string相关
// 这里面封装了跟string相关的一些工具代码
// 字符串反转
const reverse = (str) => str.split('').reverse().join('');
console.log(reverse('hello world')); // dlrow olleh
console.log(reverse('elon musk')); // ksum nole
// 大写字符串
const capitalize = (s) => s.charAt(0).toUpperCase() + s.slice(1);
console.log(capitalize('lorem ipsum')); // Lorem ipsum
// 字符串转换: 将字符串转换为带"-"的连字字符串
const slugify = (str) => str.toLowerCase().replace(/\s+/g, '-').replace(/[^\w-]+/g, '');
console.log(slugify('Hello World')); // hello-world
// 字符串转换: 将连字字符串转换为骆峰字符串
const snakeToCamel = (s) => s.toLowerCase().replace(/(_\w)/g, (w) => w.toUpperCase().substring(1));
console.log(snakeToCamel('foo_bar')); // fooBar
// 字符串转换: 将大写字符串转换为小写
const decapitalize = (str) => `${str.charAt(0).toLowerCase()}${str.slice(1)}`;
console.log(decapitalize('Hello world')); // -> hello world
// 随机数字符串: 根据当前时间生成随机数字符串。
const randomNumberString = () => new Date().getTime() + Math.random().toString(36).slice(2);
console.log(randomNumberString()); // 生成的是当前时间的毫秒数加36进制的数字字符串
// 删除字符串的尾部斜杠
const removeTrailingSlash = (value) => value && value.charAt(value.length - 1) === '/' ? value.slice(0, -1) : value;
console.log(removeTrailingSlash('foo-bar/')); // foo-bar
// 生成随机的十六进制颜色
const randomHexColor = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, '0')}`;
console.log(randomHexColor());
5、array相关
// 这里面封装了跟array相关的一些工具代码
// 检查数组是否为空
const isArrayEmpty = (arr) => Array.isArray(arr) && !arr.length;
console.log(isArrayEmpty(333)); // false
console.log(isArrayEmpty([])); // true
console.log(isArrayEmpty([1, 2, 3])); // false
// 随机打乱数组
const shuffleArray = (arr) => arr.sort(() => Math.random() - 0.5);
console.log(shuffleArray([1, 2, 3, 4, 5])); // 输出打乱后的数组
// 获取数组的随机项
const randomItem = (arr) => arr[(Math.random() * arr.length) | 0];
console.log(randomItem([1, 2, 3, 4, 5])); // 随机输出一项
6、object相关
// 这里面封装了跟object相关的一些工具代码
// 检查对象/数组(本质上就是对象)是否为空
const isObjectEmpty = (obj) => obj && Object.keys(obj).length === 0;
console.log(isObjectEmpty({})); // -> true
console.log(isObjectEmpty({ foo: 'bar' })); // -> false
console.log(isObjectEmpty([])); // -> true
console.log(isObjectEmpty([1, 2, 3])); // -> false
// 封装清空js对象的方法
const clearObject = function (data){
for(let key in data){
data[key] = '';
}
return data;
}
console.log(clearObject({ foo: 'bar' }))
7、其他
// async + await
async function awaitFunc () {
// ms是毫秒 wait实现等待ms毫秒
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
console.log("before wait");
await wait(3000); // waiting 3 second
console.log("after wait");
}
awaitFunc();