48个实用JavaScript单行代码
1. 生成随机字符串
当我们需要一个唯一id时,通过Math.random创建一个随机字符串简直不要太方便噢!!!
const randomString = () => Math.random().toString(36).slice(2)
randomString() // gi1qtdego0b
randomString() // f3qixv40mot
randomString() // eeelv1pm3ja
2.转义HTML特殊字符
解决XSS方法之一就是转义HTML。
const escape = (str) => str.replace(/[&<>"']/g, (m) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[m]))
escape('<div class="medium">Hi Medium.</div>')
// <div class="medium">Hi Medium.</div>
3.单词首字母大写
const uppercaseWords = (str) => str.replace(/^(.)|\s+(.)/g, (c) => c.toUpperCase())
uppercaseWords('hello world'); // 'Hello World'
4.将字符串转换为小驼峰
const toCamelCase = (str) => str.trim().replace(/[-_\s]+(.)?/g, (_, c) => (c ? c.toUpperCase() : ''));
toCamelCase('background-color'); // backgroundColor
toCamelCase('-webkit-scrollbar-thumb'); // WebkitScrollbarThumb
toCamelCase('_hello_world'); // HelloWorld
toCamelCase('hello_world'); // helloWorld
5.删除数组中的重复值
使用Set数据类型来对数组去重
const removeDuplicates = (arr) => [...new Set(arr)]
console.log(removeDuplicates([1, 2, 2, 3, 3, 4, 4, 5, 5, 6]))
// [1, 2, 3, 4, 5, 6]
6.铺平一个数组
const flat = (arr) =>
[].concat.apply(
[],
arr.map((a) => (Array.isArray(a) ? flat(a) : a))
)
// Or
const flat = (arr) => arr.reduce((a, b) => (Array.isArray(b) ? [...a, ...flat(b)] : [...a, b]), [])
flat(['cat', ['lion', 'tiger']]) // ['cat', 'lion', 'tiger']
7.移除数组中的假值
const removeFalsy = (arr) => arr.filter(Boolean)
removeFalsy([0, 'a string', '', NaN, true, 5, undefined, 'another string', false])
// ['a string', true, 5, 'another string']
8.确认一个数字是奇数还是偶数
const isEven = num => num % 2 === 0
isEven(2) // true
isEven(1) // false
9.获取两个数字之间的随机数
const random = (min, max) => Math.floor(Math.random() * (max - min + 1) + min)
random(1, 50) // 25
random(1, 50) // 34
10.计算平均值
const average = (...args) => args.reduce((a, b) => a + b) / args.length;
average(1, 2, 3, 4, 5); // 3
11.将数字截断到固定的小数点
const round = (n, d) => Number(Math.round(n + "e" + d) + "e-" + d)
round(1.005, 2) //1.01
round(1.555, 2) //1.56
12.计算两个日期之间天数
const diffDays = (date, otherDate) => Math.ceil(Math.abs(date - otherDate) / (1000 * 60 * 60 * 24));
diffDays(new Date("2021-11-3"), new Date("2022-2-1")) // 90
13.从日期中获取是一年中的哪一天
const dayOfYear = (date) => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / (1000 * 60 * 60 * 24))
dayOfYear(new Date()) // 74
14.获取一个随机的颜色值
const randomColor = () => `#${Math.random().toString(16).slice(2, 8).padEnd(6, '0')}`
randomColor() // #9dae4f
randomColor() // #6ef10e
15.将RGB颜色转换为十六进制颜色值
const rgbToHex = (r, g, b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)
rgbToHex(255, 255, 255) // '#ffffff'
16.清除所有的cookie
const clearCookies = () => document.cookie.split(';').forEach((c) => (document.cookie = c.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date().toUTCString()};path=/`)))
17.检测黑暗模式
const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
18.交换两个变量的值
[foo, bar] = [bar, foo]
19.暂停一会
const pause = (millis) => new Promise(resolve => setTimeout(resolve, millis))
const fn = async () => {
await pause(1000)
console.log('fatfish') // 1s later
}
fn()
20.知道一个日期是否对应于当前日期
将两个日期转换为相同格式并进行比较
<date> 是一个 Date 实例。
const isCurrentDay = (date) => new Date().toISOString().slice(0, 10) === date.toISOString().slice(0, 10);
21.如何知道一个日期是否在两个日期之间
检查过去的日期是否在最小-最大范围内。
<min>、<max> 和 <date> 是 Date 实例。
const isBetweenTwoDates = ( min, max, date) => date.getTime() >= min.getTime() && date.getTime() <= max.getTime();
22.如何知道约会是否在周末
getDay 方法返回一个介于 0 和 6 之间的数字,表示给定日期是星期几。
<date> 是一个 Date 实例。
const isWeekend = ( date ) => date.getDay() === 6 || date.getDay() === 0;
23. 检查日期是否在一年内
类似于我们过去检查日期是否与当前日期相对应的情况。在这种情况下,我们获取年份并进行比较。
<date> 和 <year> 是两个 Date 实例。
const isInAYear = (date, year) => date.getUTCFullYear() === new Date(`${year}`).getUTCFullYear();
24.将小时转换为 AM-PM 格式
我们可以用数学表达式来判断经过的时间是否小于或等于13小时,从而判断是“上午”还是“下午”。
const toAMPMFormat= (h) => `${h % 12 === 0 ? 12 : h % 12}${h < 12 ? ' am.' : ' pm.'}`;
25.句子首字母大写
我们将第一个字母转换为大写字母,然后使用 <join.> 附加句子的其余字母
const capitalize = ([first, ...rest]) => `${first.toUpperCase()}${rest.join('')}`;
26.将一封信转换成他的同事表情符号
const letterToEmoji = c => String.fromCodePoint(c.toLowerCase().charCodeAt() + 127365);
27.如何判断一个字符串是不是回文
const isPalindrome = (str) => str.toLowerCase() === str.toLowerCase().split('').reverse().join('');
28.如何计算一个数的阶乘
const getFactorial = (n) => (n <= 1 ? 1 : n * getFactorial(n - 1));
29.如何获得一个数的斐波那契数列
const getFibonacci = (n, memo = {}) => memo[n] || (n <= 2 ? 1 : (memo[n] = getFibonacci(n - 1, memo) + getFibonacci(n - 2, memo)));
30.将一个数组复制到另一个数组
const copyToArray = (arr) => [...arr];
31.从数组中获取唯一元素
const getUnique = (arr) => [...new Set(arr)];
32.随机排列数组
以下代码段以非常有效的方式打乱数组。
const shuffle = (arr) => arr.sort(() => Math.random() - 0.5);
33.按属性对数组进行分组
const groupBy = (arr, groupFn) => arr.reduce( (grouped, obj) => ({...grouped, [groupFn(obj)]: [...(grouped[groupFn(obj)] || []), obj], }),{});
34.反转字符串
我们可以利用内置的 Array 方法,如 reverse() 和 join() 来创建一个做同样事情的单行代码。
const reverseString = (str) => str.split('').reverse().join('');
35.检查两个数组是否包含相同的值
我们可以使用 Array.sort() 和 Array.join() 方法来检查两个数组是否包含相同的值。
const containSameValues= (arr1, arr2) => arr1.sort().join(',') === arr2.sort().join(',');
36.转换为华氏温度
const toFahrenheit= (celsius) => (celsius * 9) / 5 + 32;
37.转换为摄氏度
const toCelsius= (fahrenheit) => (fahrenheit- 32) * 5 / 9;
38.清除浏览器的所有cookies
const clearAllCookies = () => document.cookie.split(';').forEach((c) => (document.cookie = c.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date().toUTCString()};path=/`)));
39.将 HEX 转换为 RGB
const toRGB= (hex) =>
hex
.replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i, (_, r, g, b) => `#${r}${r}${g}${g}${b}${b}`)
.substring(1)
.match(/.{2}/g)
.map((x) => parseInt(x, 16));
40.将 RGB 转换为 HEX
const toHEX = (r,g,b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
41.检查函数是否为异步函数
const isAsyncFunction = (f) => Object.prototype.toString.call(f) === '[object AsyncFunction]';
42.如何知道一段代码是否在浏览器中运行
const runningInBrowser = typeof window === 'object' && typeof document === 'object';
43.如何知道一段代码是否在node中运行
const runningInNode= typeof process !== 'undefined' && process.versions != null && process.versions.node != null;
44.检测暗模式
这是一种非常方便的方法来检查用户是否在其浏览器上启用了黑暗模式
const isDarkMode = () => window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches;
45.滚动到顶部
滚动元素的一种单行方法是使用 <scrollIntoView> 方法。
const toTop = (element) =>
element.scrollIntoView({ behavior: "smooth", block: "start" });
46.滚动到底部
const toBottom = (element) =>
element.scrollIntoView({ behavior: "smooth", block: "end" });
47.将 JSON 转换为map
这个函数可以让我们以简单的方式将 Map 对象转换为 JSON 字符串
const jsonToMap = (json) => new Map(Object.entries(JSON.parse(json)));
48.生成一个128位的UUID
此函数允许我们生成具有 128 位值的 UUID,用于唯一标识对象或实体。
const generateUUID = (a) => a ? (a ^ ((Math.random() * 16) >> (a / 4))).toString(16) : ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace( /[018]/g, generateUUID);