编程必备!25个让你眼前一亮的JavaScript代码技巧

开发 前端
JavaScript一行代码是节省时间和代码的强大方式。它们可以用来在一行代码中执行复杂的任务,这对其他开发人员来说非常令人印象深刻。

学习强大的JavaScript一行代码,能够节省你的时间和代码量。

1. 将内容复制到剪贴板

为了提高网站的用户体验,我们经常需要将内容复制到剪贴板,以便用户可以将其粘贴到指定位置。

const copyToClipboard = (content) => navigator.clipboard.writeText(content)
copyToClipboard("Hello fatfish")

2. 获取鼠标选中内容

你以前遇到过这种情况吗?我们需要获取用户选择的内容。

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

3. 打乱一个数组

打乱一个数组?这在彩票程序中非常常见,但它并不是真正的随机。

const shuffleArray = array => array.sort(() => Math.random() - 0.5)
shuffleArray([ 1, 2,3,4, -1, 0 ]) // [3, 1, 0, 2, 4, -1]

4.将rgba转换为十六进制

我们可以将rgba和十六进制颜色值互相转换。

const rgbaToHex = (r, g, b) => "#" + [r, g, b].map(num => parseInt(num).toString(16).padStart(2, '0')).join('')
rgbaToHex(0, 0 ,0) // #000000
rgbaToHex(255, 0, 127) //#ff007f

5.将十六进制转换为rgba

const hexToRgba = hex => {
  const [r, g, b] = hex.match(/\w\w/g).map(val => parseInt(val, 16))
  return `rgba(${r}, ${g}, ${b}, 1)`;
}
hexToRgba('#000000') // rgba(0, 0, 0, 1)
hexToRgba('#ff007f') // rgba(255, 0, 127, 1)

6.获取多个数字的平均值

使用reduce函数,我们可以非常方便地得到一组数组的平均值。

const average = (...args) => args.reduce((a, b) => a + b, 0) / args.length
average(0, 1, 2, -1, 9, 10) // 3.5

7.检查一个数字是偶数还是奇数

怎么判断一个数字是奇数还是偶数?

const isEven = num => num % 2 === 0
isEven(2) // true
isEven(1) // false

8.在数组中去重元素

使用Set来删除数组中的重复元素,会让这个过程变得非常简单。

const uniqueArray = (arr) => [...new Set(arr)]
uniqueArray([ 1, 1, 2, 3, 4, 5, -1, 0 ]) // [1, 2, 3, 4, 5, -1, 0]

9.检查一个对象是否为空对象

const isEmpty = obj => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object
isEmpty({}) // true
isEmpty({ name: 'fatfish' }) // false

10.反转字符串

const reverseStr = str => str.split('').reverse().join('')
reverseStr('fatfish') // hsiftaf

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

const dayDiff = (d1, d2) => Math.ceil(Math.abs(d1.getTime() - d2.getTime()) / 86400000)
dayDiff(new Date("2023-06-23"), new Date("1997-05-31")) // 9519

12. 找出日期所在的年份中的天数

const dayInYear = (d) => Math.floor((d - new Date(d.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24)
dayInYear(new Date('2023/06/23'))// 174

13.将字符串的首字母大写

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

14.生成指定长度的随机字符串

const generateRandomString = length => [...Array(length)].map(() => Math.random().toString(36)[2]).join('')
generateRandomString(12) // cysw0gfljoyx
generateRandomString(12) // uoqaugnm8r4s

15.在两个整数之间获取一个随机整数

const random = (min, max) => Math.floor(Math.random() * (max - min + 1) + min)
random(1, 100) // 27
random(1, 100) // 84
random(1, 100) // 55

16.指定位数四舍五入

const round = (n, d) => Number(Math.round(n + "e" + d) + "e-" + d)
round(3.1415926, 3) //3.142
round(3.1415926, 1) //3.1

17.清除所有的cookies

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

18.检测是否为暗黑模式

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

19.滚动到页面顶部

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

20.判断是否为苹果设备

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

21.随机布尔值

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

22.获取变量的类型

const typeOf = (obj) => Object.prototype.toString.call(obj).slice(8, -1).toLowerCase()
typeOf('')     // string
typeOf(0)      // number
typeOf()       // undefined
typeOf(null)   // null
typeOf({})     // object
typeOf([])     // array
typeOf(0)      // number
typeOf(() => {})  // function

23.判断当前选项卡是否处于活动状态

const checkTabInView = () => !document.hidden

24.检查元素是否处于焦点状态

const isFocus = (ele) => ele === document.activeElement

25. 随机IP

const generateRandomIP = () => {
  return Array.from({length: 4}, () => Math.floor(Math.random() * 256)).join('.');
}
generateRandomIP() // 220.187.184.113
generateRandomIP() // 254.24.179.151

总结

JavaScript一行代码是节省时间和代码的强大方式。它们可以用来在一行代码中执行复杂的任务,这对其他开发人员来说非常令人印象深刻。

在本文中,我们向您展示了25个厉害的JavaScript一行代码,这些代码将让您看起来像个专家。我们还提供了一些关于如何编写自己的JavaScript一行代码的技巧。

责任编辑:武晓燕 来源: 大迁世界
相关推荐

2017-03-06 18:35:22

VRAR应用

2021-08-17 11:20:25

Vue前端技巧

2022-12-19 08:23:24

2021-06-30 09:56:24

MySQL数据库索引

2022-07-28 15:46:08

Linux工具

2023-08-10 08:16:41

Hash技术哈希表

2022-12-09 09:39:20

Vue3Vue2

2024-03-14 17:41:25

AIGC人工智能应用

2022-02-28 23:37:16

iOS苹果系统

2016-01-21 10:55:04

2024-01-03 15:59:56

Linux发行版

2023-07-11 15:43:16

JavaScript技巧

2024-03-07 08:22:32

CSS变量代码

2020-06-17 09:15:57

MySQLSQL数据库

2011-05-06 11:09:01

打印机使用技巧

2017-10-13 19:20:26

PythonGitHub年度报告

2018-01-29 19:33:11

程序员项目开发

2020-11-23 10:02:04

开发者

2022-07-22 10:06:17

JavaScript代码
点赞
收藏

51CTO技术栈公众号