当前位置: 首页 > 科技观察

12 个JavaScript常用技巧,让你看起来更像个专业人士

时间:2023-03-12 03:42:48 科技观察

12种常见的JavaScript技巧,让您看起来更像专业人士您可以提高工作效率。1.判断一个数是奇数还是偶数模运算符%做得很好。constIsEven=numnum%2===0;console.log(IsEven(2));//Result:trueconsole.log(IsEven(3));//Result:false2.检查日期是否有效day确定日期是否为工作日。constisWorkday=(date)=>date.getDay()%6!==0;console.log(isWorkday(新日期("2022/10/17")));//结果:true(星期一)控制台。日志(isWorkday(新日期(“2022/10/16”)));//Result:false(Sumday)3.得到一个随机的布尔值(true/false)用Math.random()返回一个0到1之间的值,然后判断是否大于0.5会得到一个带正确或错误的概率为50%。constrandomBool=()Math.random()>=0.5;console.log(randomBool());4.从date对象中获取时间使用Date对象的.toTimeString()方法将其转换成时间字符串,然后截取时间字符串。consttimeBeginDate=datedate.toTimeString().slice(0,8);console.log(timeBeginDate(新日期(2022,8,10,15,30,21)));//结果:“15:30:21”console.log(timeBeginDate(newDate()));//结果:返回当前时间5,滚动到页面顶部window.scrollTo()会滚动到指定坐标,如果坐标设置为(0,0),则返回到页面顶部。consttoTop=()window.scrollTo(0,0);到达顶点();6.反转字符串的方法有很多种反转字符串的方法有很多种,这里介绍最简单的一种,使用split()、reverse()和join()constreverse=strstr.split('').reverse()。加入('');console.log(reverse('hellomaxwell'));//结果:llewxamolleh7。判断当前标签页是否是可以看出浏览器可以打开很多标签页,下面的代码段是判断当前标签页是否是活动标签页。constisBrowserTabInView=()document.hidden;isBrowserTabInView();8.检查指定元素是否获得焦点可以使用document.activeElement判断元素是否获得焦点。constelementIsFocus=(el)=>(el===document.activeElement);elementIsFocus(anyElement)//如果处于焦点则返回True,否则返回False9.判断当前用户是否支持触摸事件consttouchSupported=()('ontouchstart'inwindow||window.DocumentTouch&&documentinstanceofwindow.DocumentTouch);}console.log(touchSupported());//如果支持触摸事件则返回True,否则返回False10.可以判断当前用户是否为苹果设备使用navigator.platform判断当前用户是否为苹果设备。constisAppleDevice=/Mac|iPod|iPhone|iPad/.test(navigator.platform);console.log(isAppleDevice);//如果是Apple设备返回True,否则返回False11。获取所有参数的平均值valuereduce()函数可用于计算所有参数的平均值。constaverage=(...args)=>args.reduce((a,b)=>varavg=average(6,10,8,12);console.log(avg);//结果:912,转换华氏度/摄氏度和温度单位打交道不用再害怕了,下面两个函数就是两个温度单位之间的相互转换。constcelsiusToFahrenheit=(celsius)=>摄氏*9/5+32;constfahrenheitToCelsius=(fahrenheit)=>(fahrenheit-32)*5/9;//示例console.log(celsiusToFahrenheit(20));//68console.log(celsiusToFahrenheit(0));//32console.log(celsiusToFahrenheit(-15));//5console.log(celsiusToFahrenheit(35));//95写在最后,以上就是我今天分享给大家的,如果觉得有用,记得点赞关注我,我会和大家分享更多实用的开发技巧。