为了提高网站的用户体验,我们经常需要将内容复制到剪贴板,以便用户可以将其粘贴到指定位置。
constcopyToClipboard=(content)=>navigator.clipboard.writeText(content)copyToClipboard("Hellofatfish")
你以前遇到过这种情况吗?我们需要获取用户选择的内容。
constgetSelectedText=()=>window.getSelection().toString()getSelectedText()
打乱一个数组?这在彩票程序中非常常见,但它并不是真正的随机。
constshuffleArray=array=>array.sort(()=>Math.random()-0.5)shuffleArray([1,2,3,4,-1,0])//[3,1,0,2,4,-1]
我们可以将rgba和十六进制颜色值互相转换。
constrgbaToHex=(r,g,b)=>"#"+[r,g,b].map(num=>parseInt(num).toString(16).padStart(2,'0')).join('')rgbaToHex(0,0,0)//#000000rgbaToHex(255,0,127)//#ff007f
consthexToRgba=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)
使用reduce函数,我们可以非常方便地得到一组数组的平均值。
constaverage=(...args)=>args.reduce((a,b)=>a+b,0)/args.lengthaverage(0,1,2,-1,9,10)//3.5
怎么判断一个数字是奇数还是偶数?
constisEven=num=>num%2===0isEven(2)//trueisEven(1)//false
使用Set来删除数组中的重复元素,会让这个过程变得非常简单。
constuniqueArray=(arr)=>[...newSet(arr)]uniqueArray([1,1,2,3,4,5,-1,0])//[1,2,3,4,5,-1,0]
constisEmpty=obj=>Reflect.ownKeys(obj).length===0&&obj.constructor===ObjectisEmpty({})//trueisEmpty({name:'fatfish'})//false
constreverseStr=str=>str.split('').reverse().join('')reverseStr('fatfish')//hsiftaf
constdayDiff=(d1,d2)=>Math.ceil(Math.abs(d1.getTime()-d2.getTime())/86400000)dayDiff(newDate("2023-06-23"),newDate("1997-05-31"))//9519
constdayInYear=(d)=>Math.floor((d-newDate(d.getFullYear(),0,0))/1000/60/60/24)dayInYear(newDate('2023/06/23'))//174
constcapitalize=str=>str.charAt(0).toUpperCase()+str.slice(1)capitalize("hellofatfish")//Hellofatfish
constgenerateRandomString=length=>[...Array(length)].map(()=>Math.random().toString(36)[2]).join('')generateRandomString(12)//cysw0gfljoyxgenerateRandomString(12)//uoqaugnm8r4s
constrandom=(min,max)=>Math.floor(Math.random()*(max-min+1)+min)random(1,100)//27random(1,100)//84random(1,100)//55
constround=(n,d)=>Number(Math.round(n+"e"+d)+"e-"+d)round(3.1415926,3)//3.142round(3.1415926,1)//3.1
constclearCookies=document.cookie.split(';').forEach(cookie=>document.cookie=cookie.replace(/^+/,'').replace(/=.*/,`=;expires=${newDate(0).toUTCString()};path=/`))
constisDarkMode=window.matchMedia&&window.matchMedia('(prefers-color-scheme:dark)').matchesconsole.log(isDarkMode)
constgoToTop=()=>window.scrollTo(0,0)goToTop()
constisAppleDevice=()=>/Mac|iPod|iPhone|iPad/.test(navigator.platform)isAppleDevice()
constrandomBoolean=()=>Math.random()>=0.5randomBoolean()
consttypeOf=(obj)=>Object.prototype.toString.call(obj).slice(8,-1).toLowerCase()typeOf('')//stringtypeOf(0)//numbertypeOf()//undefinedtypeOf(null)//nulltypeOf({})//objecttypeOf([])//arraytypeOf(0)//numbertypeOf(()=>{})//function
constcheckTabInView=()=>!document.hidden
constisFocus=(ele)=>ele===document.activeElement
constgenerateRandomIP=()=>{returnArray.from({length:4},()=>Math.floor(Math.random()*256)).join('.');}generateRandomIP()//220.187.184.113generateRandomIP()//254.24.179.151
在本文中,我们向您展示了25个厉害的JavaScript一行代码,这些代码将让您看起来像个专家。我们还提供了一些关于如何编写自己的JavaScript一行代码的技巧。