js非常实用的一行代码

一,日期处理

检查日期是否有效,用于检测给出的日期是否有效

const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf());
isDateValid("DEcember 17, 1995 03:24:00);

计算两个日期之间的间隔,用于计算两个日期之间的间隔时间

const dayDif = (date1,date2) => Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000)
dayDif(new Date("2021-11-2"), new Date("2022-6-8"))

查找日期位于一年中的第几天,用于检测给出的日期位于今年的第几天

const dayOfYear = (date) => Math.floor((date - new date(date.getFullYear(),0,0)) / 1000 / 60 / 60 / 24)
dayOfYear(new date());

时间格式化,可以用于将时间转化为hour:minutes:seconds的格式

const timeFromDate = date => date.toTimeString().slice(0,8);
timeFromDate(new Date(2021, 11, 2, 12, 30, 0));
timeFromDate(new date());

二,字符串处理

字符串首字母大写,用于将英文字符串的首字母大写处理

const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1)
capitalize("hello world")

翻转字符串,一个字符串进行翻转操作返回翻转后的字符串

const reverse = str => str.split('').reverse().join('');
reverse('hello world');

随机生成字符串,用于生成一个随机字符串

const randomString = () => Math.random().toString(36).slice(2);
randomString();

截断字符串,可以从指定长度处截断字符串

const truncateString = (String,length) => String.length < length ? String : '${string.slice(0, length - 3)}...';
truncateString('Hi, I should be truncateb I am too loooong', 36)

去除字符串中的HTML,用于去除字符串中的HTML元素

const stripHtml = html => (new DOMParser().parseFromString(html, 'text/html')).body.textContent || '';

三,数组处理

从数组中移出重复项,用于移出数组中的重复项

const removeDuplicates = (arr) => [...new Set(arr)];
console.log(removeDuplicates([1, 2, 2, 3, 3, 4, 4, 5, 5, 6]));

判断数组是否为空,用于判断一个数组是否为空数组,它将返回一个布尔值

const isNotEmpty = arr => Array.isArray(arr) && arr.length > 0;
isNotEmpty([1, 2, 3]);

合并两个数组,可以使用下面两个方法来合并两个数组

const merge = (a, b) => a.concat(b);
const merge = (a, b) => [...a, ...b];

四,数字操作

判断一个数是奇数还是偶数

const isEven = num => num % 2 ===0;
isEven(996);

获得一组数平均值

const average = (...args) => args.reduce((a, b) => a+b) / args.length;
average(1, 2, 3, 4, 5);

获取两个整数之间的随机整数

const random = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);
random(1, 50);

指定位数四舍五入

const round = (n, d) => Number(Math.round(n + "e" + d) + "e-" + d)
round(1.005, 2)
round(1.555, 2)

五,颜色操作

将RGB转化为十六进制

const rgbToHex = (r, g, b) => "#" +((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
rgbToHex(255, 255, 255);

获取随机十六进制颜色

const randomHex = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`;
randomHex();

六,浏览器操作

复制内容到剪切板

const copyToClipboard = (test) => navigator.clipboard.writeText(test);
copyToClipboard("Hello World");

清除所有cookie

const cleaCookies = document.cookie.split(';').forEach(cookie => document.cookie = cookie.replace(/^ +/,'').repeat(/=.*/,'=;expires=${new Date(0).toUTCString()};path=/'));

获取选中的文本

const getSelectedText = () => window.getSelection().toString();
getSelectedText();

检测是否为黑暗模式

const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
console.log(isDarkMode);

滚动到页面顶部

const goToTop = () => window.scrollTo(0, 0);
goToTop();

判断当前标签页是否激活

const isTabInView = () => !document.hidden;

判断当前是否是苹果设备

const isAppleDevice = () => /Mac|ipod|iphone|ipad/.test(navigator.platform);
isAppleDevice();

判断是否滚动到页面底部

const scrolledToBottom = () => document.documentElement.clientHeight + window.screenY >= document.documentElement.scrollHeight;

重定向到一个新的URL

const redirect = url => location.href = url
redirect("https://chimengblog.com/")

打开浏览器的打印框

const showPrintDialog = () => window.print()

七,其他操作

随机布尔值,可以返回一个随机的布尔值(使用Math.random()可以获得0-1的随机数与0.5进行比较,就有一半的概率获得真值或者假值)

const randomBoolean = () => Math.random() >= 0.5;
randomBoolean();

变量交换

[foo, bar] = [bar, foo];

检测对象是否为空

const isEmpty = obj => Reflect.ownKeys(onj).length === 0 && obj.constructor === Object;
© 版权声明
THE END
喜欢就支持一下吧
点赞10赞赏 分享
评论 共2条

请登录后发表评论