19个 JavaScript 单行代码技巧,让你看起来像个专业人士
创始人
2025-06-28 03:50:56
0

今天这篇文章跟大家分享18个JS单行代码,你只需花几分钟时间,即可帮助您了解一些您可能不知道的 JS 知识,如果您已经知道了,就当作复习一下,古人云,温故而知新嘛。

现在,我们就开始今天的内容。

1. 生成随机字符串

我们可以使用Math.random来生成一个随机字符串,当我们需要唯一的ID时,这非常方便。

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('
Hi Medium.
') //
Hi Medium.

3.将字符串中每个单词的第一个字符大写

此方法用于将字符串中每个单词的第一个字符大写。

const uppercaseWords = (str) => str.replace(/^(.)|\s+(.)/g, (c) => c.toUpperCase())
uppercaseWords('hello world'); // 'Hello World'

谢谢克里斯托弗·斯特罗利亚·戴维斯,以下是他提供的更简单的方法。

const uppercaseWords = (str) => str.replace(/^(.)|\s+(.)/g, (c) => c.toUpperCase())

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. 获取参数的平均值

我们可以使用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.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. pause for a while

const pause = (millis) => new Promise(resolve => setTimeout(resolve, millis))
const fn = async () => {
  await pause(1000)
console.log('fatfish') // 1s later
}
fn()

最后

以上就是我今天与你分享的关于JS的19个一行代码技巧,希望能够对您有所帮助,感谢您的阅读,祝编程愉快!

相关内容

热门资讯

如何允许远程连接到MySQL数... [[277004]]【51CTO.com快译】默认情况下,MySQL服务器仅侦听来自localhos...
如何利用交换机和端口设置来管理... 在网络管理中,总是有些人让管理员头疼。下面我们就将介绍一下一个网管员利用交换机以及端口设置等来进行D...
施耐德电气数据中心整体解决方案... 近日,全球能效管理专家施耐德电气正式启动大型体验活动“能效中国行——2012卡车巡展”,作为该活动的...
20个非常棒的扁平设计免费资源 Apple设备的平面图标PSD免费平板UI 平板UI套件24平图标Freen平板UI套件PSD径向平...
德国电信门户网站可实时显示全球... 德国电信周三推出一个门户网站,直观地实时提供其安装在全球各地的传感器网络检测到的网络攻击状况。该网站...
为啥国人偏爱 Mybatis,... 关于 SQL 和 ORM 的争论,永远都不会终止,我也一直在思考这个问题。昨天又跟群里的小伙伴进行...
《非诚勿扰》红人闫凤娇被曝厕所... 【51CTO.com 综合消息360安全专家提醒说,“闫凤娇”、“非诚勿扰”已经被黑客盯上成为了“木...
2012年第四季度互联网状况报... [[71653]]  北京时间4月25日消息,据国外媒体报道,全球知名的云平台公司Akamai Te...