查看原文
其他

19 个杀手级 JavaScript 单行代码,让你看起来像专业人士


英文 | https://javascript.plainenglish.io/19-killer-javascript-one-liners-thatll-make-you-look-like-a-pro-fce9b524e45e


1.生成随机字符串
我们可以使用 Math.random() 来生成一个随机字符串,当我们需要一个唯一的 ID 时非常方便。
const randomString = () => Math.random().toString(36).slice(2)
randomString() // gi1qtdego0brandomString() // f3qixv40motrandomString() // eeelv1pm3ja
2.转义HTML特殊字符
如果你了解 XSS,其中一种解决方案是转义 HTML 字符串。
const escape = (str) => str.replace(/[&<>"']/g, (m) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[m]))
escape('<div class="medium">Hi Medium.</div>') // &lt;div class=&quot;medium&quot;&gt;Hi Medium.&lt;/div&gt
3.大写字符串中每个单词的第一个字符
此方法用于将字符串中每个单词的第一个字符大写。
const uppercaseWords = (str) => str.replace(/^(.)|\s+(.)/g, (c) => c.toUpperCase())
uppercaseWords('hello world'); // 'Hello World'
4.将字符串转换为camelCase
const toCamelCase = (str) => str.trim().replace(/[-_\s]+(.)?/g, (_, c) => (c ? c.toUpperCase() : ''));
toCamelCase('background-color'); // backgroundColortoCamelCase('-webkit-scrollbar-thumb'); // WebkitScrollbarThumbtoCamelCase('_hello_world'); // HelloWorldtoCamelCase('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)) )// Orconst 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) // trueisEven(1) // false
9. 获取两个数字之间的随机整数
此方法用于获取两个数字之间的随机整数。
const random = (min, max) => Math.floor(Math.random() * (max - min + 1) + min)
random(1, 50) // 25random(1, 50) // 34
10. 获取参数的平均值
我们可以使用 reduce 方法来获取我们在此函数中提供的参数的平均值。
const average = (...args) => args.reduce((a, b) => a + b) / args.length;
average(1, 2, 3, 4, 5); // 3
11. 将数字截断为固定小数点
使用 Math.pow() 方法,我们可以将一个数字截断为我们在函数中提供的某个小数点。
const round = (n, d) => Number(Math.round(n + "e" + d) + "e-" + d)
round(1.005, 2) //1.01round(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() // #9dae4frandomColor() // #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.清除所有cookies
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()
最后
以上就是我今天跟你分享的19个JavaScript的单行代码,希望对你有用,如果你觉得有帮助的话,请点赞我,关注我,并与你的开作者朋友分享这篇文章,最后,感谢你的阅读,祝编程愉快!

学习更多技能

请点击下方公众号

您可能也对以下帖子感兴趣

文章有问题?点此查看未经处理的缓存