Less is more
目录
1、切换布尔值
const toggle = (value) => value = !value
2、范围内的随机数
const randomNumberInRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
3、正数
const getPositiveNumber = (number) => Math.max(number, 0)
4、奇数还是偶数
const isEven = num => num % 2 === 0;
console.log(isEven(2)); // True
5、求平均值
const average = (...args) => args.reduce((a, b) => a + b) / args.length;
average(1, 2, 3, 4); // 2.5
6、四舍五入到小数点
const toFixed = (n, fixed) => ~~(Math.pow(10, fixed) * n) / Math.pow(10, fixed);
toFixed(25.198726354, 6); // 25.198726
7、字符串大写
const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1)
8、随机字符串
const randomString = () => Math.random().toString(36).slice(2);
randomString();
9、字符串反转
const reverse = str => str.split('').reverse().join('');
reverse('hello world'); // 'dlrow olleh'
10、是否为数组
const isArray = (arr) => Array.isArray(arr)
11、数组元素随机排序
const sortRandom = (arr) => arr.sort(() => Math.random() - 0.5)
12、获取数组唯一值
const uniqueValues = (arr) => [...new Set(arr)]
13、检查数组中的所有项是否满足某个条件
const isOldEnough = (age) => age >= 18
const olderPeople = [39, 51, 33, 65, 49]
olderPeople.every(isOldEnough) // true
// every 方法检查数组中的所有项是否满足某个条件
// some() 方法检查数组中的一个元素来满足某个条件
14、将所有值转换为数组
const arrayToNumbers = (arr) => arr.map(Number)
const numbers = arrayToNumbers(['0', '1', '2', '3'])
const arrayToBooleans = (arr) => arr.map(Boolean)
const booleans = arrayToBooleans(numbers)
15、获取数组的交集
const intersection = (a, ...arr) => [...new Set(a)].filter((v) => arr.every((b) => b.includes(v)))
intersection([1, 2, 3], [2, 3, 4, 7, 8], [1, 3, 9]) // [3]
16、数组是否为空
const isNotEmpty = arr => Array.isArray(arr) && arr.length > 0;
isNotEmpty([1, 2, 3]); // true
17、从 URL 获取search参数对象
Object.fromEntries(new URLSearchParams(window.location.search))
18、打印预览
const showPrintDialog = () => window.print()
19、将文本复制到剪贴板
const copyTextToClipboard = async (text) => {
await navigator.clipboard.writeText(text)
}
20、计算两个日期之间的天数
const daysBetweenDates = (dateA, dateB) => {
const timeDifference = Math.abs(dateA.getTime() - dateB.getTime())
return Math.floor(timeDifference / (3600 * 24 * 1000))
}
daysBetweenDates(new Date('2020/10/21'), new Date('2021/10/29')) // 373
21、日期是否工作日
const isWeekday = (date) => date.getDay() % 6 !== 0;
console.log(isWeekday(new Date(2021, 0, 10))); // false (Sunday)
22、日期是否合法
const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf());
isDateValid("December 17, 1995 03:24:00"); // true
23、查找日期位于一年中的第几天
const dayOfYear = (date) => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);
dayOfYear(new Date()); // 272
24、获取某个月的天数
const daysInMonth = (month, year) => new Date(year, month, 0).getDate()
daysInMonth(2, 2024) // 29
25、交换变量值
let personA = "Laura"
let personB = "John"
[personA, personB] = [personB, personA]
26、一个空格替换多个空格
const replaceSpaces = (str) => str.replace(/\s\s+/g, ' ')
replaceSpaces('Too many spaces') // 'Too many spaces'
27、对象是否相等
const isEqual = (...objects) => objects.every(obj => JSON.stringify(obj) === JSON.stringify(objects[0]))
isEqual({ name: 'Frank', age: 32 }, { name: 'Frank', age: 32 }, { name: 'Frank', age: 32 }) // true
28、对象是否为空
const isEmpty = obj => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object;
29、Cookie
// 获取浏览器Cookie的值
const cookie = name => `; ${document.cookie}`.split(`; ${name}=`).pop().split(';').shift();
cookie('xx');
// 清除全部Cookie
const clearCookies = document.cookie.split(';').forEach(cookie => document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date(0).toUTCString()};path=/`));
30、颜色RGB转十六进制
const rgbToHex = (r, g, b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
rgbToHex(0, 51, 255); // #0033ff
31、随机十六进制颜色
const randomHex = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`;
console.log(randomHex());
32、回到顶部
const goToTop = () => window.scrollTo(0, 0);
goToTop();
33、获取用户选择的文本
const getSelectedText = () => window.getSelection().toString();
getSelectedText();
34、检查当前设备是否处于暗模式
const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
35、检查元素当前是否处于焦点
const elementIsInFocus = (el) => (el === document.activeElement);
36、检查当前是否支持触摸事件
const touchSupported = () => {
('ontouchstart' in window || window.DocumentTouch && document instanceof window.DocumentTouch);
}
37、检查当前是否Apple设备
const isAppleDevice = /Mac|iPod|iPhone|iPad/.test(navigator.platform);
未完待续。。。