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

13行JavaScript代码让你看起来像个高手

时间:2023-03-12 00:54:06 科技观察

Javascript可以做很多令人惊奇的事情,而且有很多东西需要学习,今天我们介绍几个简短而整洁的代码片段。得到一个随机的布尔值(True/False)使用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,0,11))));//Result:true(Monday)console.log(isWeekday(newDate(2021,0,10)));//Result:false(Sunday)字符串反转的方法有很多种,这里介绍最简单的,使用split(),reverse()和join()constreverse=str=>str.split('').reverse().join('');reverse('helloworld');//Result:'dlrorolleh'判断当前标签页是否可见浏览器可以打开很多标签页,下面代码段是判断当前标签页是否为活动标签页constisBrowserTabInView=()=>document.hidden;isBrowserTabInView();判断数是奇数还是偶数取模运算符%可以完成这个任务constisEven=num=>num%2===0;console.log(isEven(2));//Result:trueconsole.log(isEven(3)));//Result:false从Date对象中获取时间使用Date对象的.toTimeString()方法将其转换为时间字符串,然后截取该字符串为consttimeFromDate=date=>date.toTimeString().slice(0,8);console.log(timeFromDate(newDate(2021,0,10,17,30,0)));//结果:"17:30:00"console.log(timeFromDate(newDate()));//结果:返回指定小数点后的当前时间consttoFixed=(n,fixed)=>~~(Math.pow(10,fixed)*n)/Math.pow(10,fixed);//ExamplestoFixed(25.198726354,1);//25.1toFixed(25.198726354,2);//25.19toFixed(25.198726354,3);//25.198toFixed(25.19872635,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());//结果:如果支持触摸事件,则返回是的,否则它会l返回False,检查当前用户是否为苹果设备。可以通过navigator.platform判断当前用户是否为苹果设备constisAppleDevice=/Mac|iPod|iPhone|iPad/.test(navigator.platform);console.log(isAppleDevice);//结果:如果是苹果window.scrollTo()会滚动到指定坐标,如果坐标设置为(0,0),会返回到页面顶部constgoToTop=()=>window.scrollTo(0,0);goToTop();//结果:会滚动到顶部得到所有参数的平均值可以使用reduce()函数计算平均值allparametersconstaverage=(...args)=>args.reduce((a,b)=>a+b)/args.length;average(1,2,3,4);//结果:2.5转换华氏度/Celsius不再害怕温度单位处理。下面两个函数是两个温度单位的相互转换。constcelsiusToFahrenheit=(celsius)=>celsius*9/5+32;/ExamplesCelsiusToFahrenheit(15);//59CelsiusToFahrenheit(0);//32CelsiusToFahrenheit(-20);//-4FahrenheitToCelsius(59);//15FahrenheitToCelsius(32);//0

猜你喜欢