25個讓你眼前一亮的JavaScript代碼技巧分享
1. 將內(nèi)容復制到剪貼板
為了提高網(wǎng)站的用戶體驗,我們經(jīng)常需要將內(nèi)容復制到剪貼板,以便用戶可以將其粘貼到指定位置。
const?copyToClipboard?=?(content)?=>?navigator.clipboard.writeText(content)
copyToClipboard("Hello?fatfish")2. 獲取鼠標選中內(nèi)容
你以前遇到過這種情況嗎?我們需要獲取用戶選擇的內(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轉(zhuǎn)換為十六進制
我們可以將rgba和十六進制顏色值互相轉(zhuǎn)換。
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)?//#ff007f5.將十六進制轉(zhuǎn)換為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ù),我們可以非常方便地得到一組數(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ù)組中去重元素
使用Set來刪除數(shù)組中的重復元素,會讓這個過程變得非常簡單。
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'?})?//?false10.反轉(zhuǎn)字符串
const?reverseStr?=?str?=>?str.split('').reverse().join('')
reverseStr('fatfish')?//?hsiftaf11.計算兩個日期之間的間隔
const?dayDiff?=?(d1,?d2)?=>?Math.ceil(Math.abs(d1.getTime()?-?d2.getTime())?/?86400000)
dayDiff(new?Date("2023-06-23"),?new?Date("1997-05-31"))?//?951912. 找出日期所在的年份中的天數(shù)
const?dayInYear?=?(d)?=>?Math.floor((d?-?new?Date(d.getFullYear(),?0,?0))?/?1000?/?60?/?60?/?24)
dayInYear(new?Date('2023/06/23'))//?17413.將字符串的首字母大寫
const?capitalize?=?str?=>?str.charAt(0).toUpperCase()?+?str.slice(1)
capitalize("hello?fatfish")??//?Hello?fatfish14.生成指定長度的隨機字符串
const?generateRandomString?=?length?=>?[...Array(length)].map(()?=>?Math.random().toString(36)[2]).join('')
generateRandomString(12)?//?cysw0gfljoyx
generateRandomString(12)?//?uoqaugnm8r4s15.在兩個整數(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.清除所有的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(()?=>?{})??//?function23.判斷當前選項卡是否處于活動狀態(tài)
const?checkTabInView?=?()?=>?!document.hidden
24.檢查元素是否處于焦點狀態(tài)
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總結(jié)
JavaScript一行代碼是節(jié)省時間和代碼的強大方式。它們可以用來在一行代碼中執(zhí)行復雜的任務,這對其他開發(fā)人員來說非常令人印象深刻。
在本文中,我們向您展示了25個厲害的JavaScript一行代碼,這些代碼將讓您看起來像個專家。我們還提供了一些關(guān)于如何編寫自己的JavaScript一行代碼的技巧。
以上就是25個讓你眼前一亮的JavaScript代碼技巧分享的詳細內(nèi)容,更多關(guān)于JavaScript技巧的資料請關(guān)注腳本之家其它相關(guān)文章
相關(guān)文章
Javacript實現(xiàn)顏色梯度變化和漸變的效果代碼
用js對導航欄的顏色做了梯度的變化處理,通過處理..獲取兩種顏色在變化時的各種顏色字符串,并且字符串的個數(shù),即獲取的頻率可以調(diào)節(jié)2013-05-05
SOSO地圖API使用(一)在地圖上畫圓實現(xiàn)思路與代碼
最近在做SOSO地圖相關(guān)開發(fā),遇到相關(guān)畫圓知識,特此簡單記錄下來,接下來講解如何在在地圖上畫圓,感興趣的朋友可以了解下2013-01-01

