13个JavaScript 一行程序,让你看起来像个专家

JAVAScript 可以做很多好玩的事,从复杂的框架到处理API,有太多的东西需要学习 。但是,它也能让我们只用一行就能做一些了不起的事情 。
1. 获得一个随机的布尔值(true/false)该函数使用Math.random()方法返回一个布尔值(true 或者 false) 。Math.random创建一个0到1之间的随机数,我们只要检查它是否高于或低于0.5,就有50%机会得到true或false 。
const randomBoolean = () => Math.random() >= 0.5;console.log(randomBoolean());2. 检查所提供的日期是否为工作日使用这种方法,我们能够检查在函数中提供的日期是否是工作日或周末的日子 。
const isWeekday = (date) => date.getDay() % 6 !== 0;console.log(isWeekday(new Date(2021, 7, 6)));// true因为是周五console.log(isWeekday(new Date(2021, 7, 7)));// false 因为是周六3.反转字符串有几种不同的方法来反转一个字符串 。这是最简单的一种,使用split()、reverse()和join()方法 。
const reverse = str => str.split('').reverse().join('');reverse('hello world');// 'dlrow olleh'4.检查当前标签是否隐藏Document.hidden (只读属性)返回布尔值,表示页面是(true)否(false)隐藏 。
const isBrowserTabInView = () => document.hidden;isBrowserTabInView();场外:无意间发现爱奇艺广告播放时间居然是在当前标签页激活的时候才会进行倒计时,离开当前标签页的时候,倒计时停止,百度一下发现document.hidden这个东东 。
document.hidden是h5新增加api使用的时候有兼容性问题 。
var hiddenif (typeof document.hidden !== "undefined") {hidden = "hidden";} else if (typeof document.mozHidden !== "undefined") {hidden = "mozHidden";} else if (typeof document.msHidden !== "undefined") {hidden = "msHidden";} else if (typeof document.webkitHidden !== "undefined") {hidden = "webkitHidden";}console.log("当前页面是否被隐藏:" + document[hidden])5. 检查一个数字是偶数还是奇数const isEven = num => num % 2 === 0;console.log(isEven(2));// trueconsole.log(isEven(3));// false6. 从一个日期获取时间const timeFromDate = date => date.toTimeString().slice(0, 8);console.log(timeFromDate(new Date(2021, 0, 10, 17, 30, 0))); // "17:30:00"console.log(timeFromDate(new Date()));// 打印当前的时间7. 保留 n 位小数const toFixed = (n, fixed) => ~~(Math.pow(10, fixed) * n) / Math.pow(10, fixed);// 事例toFixed(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.1987268. 检查当前是否有元素处于焦点中我们可以使用document.activeElement属性检查一个元素是否当前处于焦点 。
const elementIsInFocus = (el) => (el === document.activeElement);elementIsInFocus(anyElement)// 如果在焦点中返回true,如果不在焦点中返回 false9. 检查当前浏览器是否支持触摸事件const touchSupported = () => {('ontouchstart' in window || window.DocumentTouch && document instanceof window.DocumentTouch);}console.log(touchSupported());// 如果支持触摸事件,将返回true,如果不支持则返回false 。10. 检查当前浏览器是否在苹果设备上const isAppleDevice = /mac|iPod|iphone|iPad/.test(navigator.platform);console.log(isAppleDevice);11. 滚动到页面顶部const goToTop = () => window.scrollTo(0, 0);goToTop();12. 获取参数的平均数值const average = (...args) => args.reduce((a, b) => a + b) / args.length;average(1, 2, 3, 4);// 2.513.华氏/摄氏转换const celsiusToFahrenheit = (celsius) => celsius * 9/5 + 32;const fahrenheitToCelsius = (fahrenheit) => (fahrenheit - 32) * 5/9;// 事例celsiusToFahrenheit(15);// 59celsiusToFahrenheit(0);// 32celsiusToFahrenheit(-20);// -4fahrenheitToCelsius(59);// 15fahrenheitToCelsius(32);// 0【13个JavaScript 一行程序,让你看起来像个专家】~完,我是刷碗智,会所按摩走起!


    推荐阅读