33个非常实用的JavaScript

2023年01月04日 1477点热度 1人点赞 0条评论

一、日期处理

1. 检查日期是否有效

const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf());
isDateValid("December 21, 2025 01:52:00"); // true

2. 计算两个日期之间的间隔

const dayDif = (date1, date2) => Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000);
dayDif(new Date(), new Date("2099-12-31")); // 28120

距离2099-12-31还有28120天,算算我是什么时候写这段代码的 ~

3. 查找日期位于一年中的第几天

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

2023年已经过去?天了~

4. 时间格式化

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

const timeFromDate = date => date.toTimeString().slice(0, 8);
timeFromDate(new Date(2023, 1, 2, 12, 30, 0)); // 12:30:00
timeFromDate(new Date()); // 返回当前时间 09:00:00

二、字符串处理

1. 字符串首字母大写

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

2. 翻转字符串

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

3. 随机字符串

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

4. 截断字符串

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

5. 去除字符串中的HTML

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

三、数组处理

1. 从数组中移除重复项

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

2. 判断数组是否为空

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

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

3. 合并两个数组

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

四、数字操作

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

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

2. 获得一组数的平均值

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

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

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

4. 指定位数四舍五入

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

五、颜色操作

1. 将RGB转化为十六机制

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

2. 获取随机十六进制颜色

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

六、浏览器操作

1. 复制内容到剪切板该方法

使用 navigator.clipboard.writeText 来实现将文本复制到剪贴板:

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

2. 清除所有cookie

该方法可以通过使用 document.cookie 来访问 cookie 并清除存储在网页中的所有 cookie:

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

3. 获取选中的文本

该方法通过内置的 getSelection 属性获取用户选择的文本:

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

4. 检测是否是黑暗模式

该方法用于检测当前的环境是否是黑暗模式,它是一个布尔值:

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

5. 滚动到页面顶部

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

6. 判断当前标签页是否激活

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

7. 判断当前是否是苹果设备

const isAppleDevice = () => /Mac|iPod|iPhone|iPad/.test(navigator.platform);
isAppleDevice();

8. 是否滚动到页面底部

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

9. 重定向到一个URL

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

10. 打开浏览器打印框

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

七、其他操作

1. 随机布尔值

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

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

2. 变量交换可以

使用以下形式在不适用第三个变量的情况下,交换两个变量的值:

[a, b] = [b, a];

3. 获取变量的类型

const trueTypeOf = (obj) => Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();

trueTypeOf(''); // string
trueTypeOf(0); // number
trueTypeOf(); // undefined
trueTypeOf(null); // null
trueTypeOf({}); // object
trueTypeOf([]); // array
trueTypeOf(0); // number
trueTypeOf(() => {}); // function

4. 华氏度和摄氏度之间的转化

const celsiusToFahrenheit = (celsius) => celsius * 9/5 + 32;
const fahrenheitToCelsius = (fahrenheit) => (fahrenheit - 32) * 5/9;

celsiusToFahrenheit(15); // 59
celsiusToFahrenheit(0); // 32
celsiusToFahrenheit(-20); // -4
fahrenheitToCelsius(59); // 15
fahrenheitToCelsius(32); // 0

5. 检测对象是否为空

const isEmpty = obj => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object;

路灯

这个人很懒,什么都没留下

文章评论