自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

25 個殺手級 JavaScript 單行代碼讓你看起來像個專業(yè)人士

開發(fā) 前端
你應該知道的25個單行代碼片段,以提升你的 JavaScript 知識技能,同時幫助你提升工作效率。

你應該知道的25個單行代碼片段,以提升你的 JavaScript 知識技能,同時幫助你提升工作效率。

那我們現(xiàn)在開始吧。

1.將內(nèi)容復制到剪貼板

為了提高網(wǎng)站的用戶體驗,我們經(jīng)常需要將內(nèi)容復制到剪貼板,以便用戶將其粘貼到指定位置。

const copyToClipboard = (content) => navigator.clipboard.writeText(content)


copyToClipboard("Hello fatfish")

2.獲取鼠標選擇

你以前遇到過這種情況嗎?

我們需要獲取用戶選擇的內(nèi)容。

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


getSelectedText()

3.打亂數(shù)組

打亂數(shù)組?這在彩票程序中很常見,但并不是真正隨機的。

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}, $, 1)`;
}


hexToRgba('#000000') // rgba(0, 0, 0, 1)
hexToRgba('#ff007f') // rgba(255, 0, 127, 1)

6.獲取多個數(shù)字的平均值

使用 reduce 我們可以非常方便地獲取一組數(shù)組的平均值。

const average = (...args) => args.reduce((a, b) => a + b, 0) / args.length


average(0, 1, 2, -1, 9, 10) // 3.5

7.檢查數(shù)字是偶數(shù)還是奇數(shù)

你如何判斷數(shù)字是奇數(shù)還是偶數(shù)?

const isEven = num => num % 2 === 0


isEven(2) // true
isEven(1) // false

8.刪除數(shù)組中的重復元素

要刪除數(shù)組中的重復元素,使用 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.獲取兩個整數(shù)之間的隨機整數(shù)

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.指定數(shù)字四舍五入

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.清除所有 cookie

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.確定是否為 Apple 設備

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.確定當前選項卡是否處于活動狀態(tài)

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

總結

以上就是我今天與你分享的25個JS單行代碼片段,希望對你有所幫助。


責任編輯:華軒 來源: web前端開發(fā)
相關推薦

2024-08-27 15:25:33

2023-06-27 23:57:06

JavaScrip技能

2023-08-01 14:36:00

JavaScript開發(fā)

2022-09-26 12:53:54

JavaScrip單行代碼

2022-11-09 15:36:11

Javascript技巧代碼

2023-07-11 15:43:16

JavaScript技巧

2025-03-17 10:42:12

2021-12-19 22:48:53

JavaScript開發(fā)代碼

2022-10-20 15:16:23

JavaScript數(shù)組技能

2024-09-13 16:19:47

2022-02-28 12:57:09

GNOMEPlasma桌面

2022-10-08 07:54:24

JavaScriptAPI代碼

2023-06-14 15:51:48

JavaScript

2020-02-26 21:57:09

Lambdajava8方法引用

2022-02-21 12:05:49

LibreOffiLinux工具欄

2023-10-10 16:20:38

JavaScript代碼技巧

2024-10-09 14:45:41

2022-06-21 14:30:16

Vim自定義Linux

2022-05-26 01:15:22

GitHub代碼快捷鍵

2020-06-29 15:00:31

UbuntumacOSLinux
點贊
收藏

51CTO技術棧公眾號