Category获取随机布尔值(真/假)此函数使用Math.random()方法返回布尔值(真或假)。Math.random创建一个介于0和1之间的随机数,我们只检查它是高于还是低于0.5,有50%的机会得到true或false。constrandomBoolean=()=>Math.random()>=0.5;console.log(randomBoolean());使用此方法检查提供的日期是否为工作日,我们可以检查函数中提供的日期是星期几还是周末。constisWeekday=(date)=>date.getDay()%6!==0;console.log(isWeekday(newDate(2021,7,6)));//true因为是星期五console.log(isWeekday(newDate(2021,7,7)));//false因为是星期六3.反转字符串反转字符串有几种不同的方法。这是最简单的一个,使用split()、reverse()和join()方法。constreverse=str=>str.split('').reverse().join('');reverse('helloworld');//'dlrowolleh'4.检查当前标签是否隐藏Document.hidden(仅Read属性)返回一个布尔值,指示页面是否隐藏(true)或不隐藏(false)。constisBrowserTabInView=()=>document.hidden;isBrowserTabInView();站外:无意中发现爱奇艺广告播放时间在当前标签激活时倒计时,当前标签激活时倒计时停止,百度找到document.hidden这个东东。document.hidden是使用h5新增api时的兼容性问题。varhiddenif(typeofdocument.hidden!=="undefined"){hidden="hidden";}elseif(typeofdocument.mozHidden!=="undefined"){hidden="mozHidden";}elseif(typeofdocument.msHidden!=="undefined"){hidden="msHidden";}elseif(typeofdocument.webkitHidden!=="undefined"){hidden="webkitHidden";}console.log("当前页面是否隐藏:"+document[hidden])检查一个数是偶数还是奇数constisEven=num=>num%2===0;console.log(isEven(2));//trueconsole.log(isEven(3));//false从日期获取时间consttimeFromDate=date=>date.toTimeString().slice(0,8);console.log(timeFromDate(新日期(2021,0,10,17,30,0)));//"17:30:00"console.log(timeFromDate(newDate()));//打印当前时间,小数点后n位consttoFixed=(n,fixed)=>~~(Math.pow(10,fixed)*n)/Math.pow(10,fixed);//casetoFixed(25.198726354,1);//25.1toFixed(25.198726354,2);//25.19toFixed(25.198726354,3);//25.198toFixed(25.198726354,4);//25.1987toFixed(25.198726354,5);//25.19872toFixed(25.198726354,6);//25.198726检查元素当前是否处于焦点我们可以使用document.activeElement属性来检查元素当前是否处于焦点constelementIsInFocus=(el)=>(el===document.activeElement);elementIsInFocus(anyElement)//聚焦返回true,非聚焦返回false检查当前浏览器是否支持触摸事件consttouchSupported=()=>{('ontouchstart'inwindow||window.DocumentTouch&&documentinstanceofwindow.DocumentTouch);}console.log(touchSupported());//如果支持触摸事件,则返回true,否则返回false。检查当前浏览器是否在苹果设备上constisAppleDevice=/Mac|iPod|iPhone|iPad/.test(navigator.platform);控制台日志(isAppleDevice);滚动到页面顶部constgoToTop=()=>window.scrollTo(0,0);转到顶部();获取参数的平均值constaverage=(...args)=>args.reduce((a,b)=>a+b)/args.length;平均值(1、2、3、4);//2.513。华氏/摄氏转换constcelsiusToFahrenheit=(celsius)=>celsius*9/5+32;constfahrenheitToCelsius=(fahrenheit)=>(fahrenheit-32)*5/9;///示例celsiusToFahrenheit(15);//59摄氏度到华氏度(0);//32摄氏度到华氏度(-20);//-4华氏度到摄氏度(59);//15华氏度到摄氏度(32);//0到这篇关于13行JavaScript的文章,这就是这篇让你看起来像专家的文章
