13 条高效实用的 JavaScript 单行代码

JavaScript能够实现不少使人惊奇的事!前端

从复杂的框架处处理API,有太多的东西能够学习。浏览器

甚至,仅用一行代码,它也能完成一些很棒的工做。框架

不信?那么请看这13条JavaScript单行代码,用上它们,会让你看起来特别专业!dom

1. 获取随机布尔值(true/false)

使用Math.random()方法可让函数返回布尔值(true或false)。Math.random会建立一个介于0和1之间的随机数,而后咱们检查这个数是大于仍是小于0.5。也就是说,有50%/50%的概率获得true或false。编辑器

如下JS代码块显示了如何使用Math.Random方法获取随机布尔值。函数

const randomBoolean = () => Math.random() >= 0.5;
console.log(randomBoolean());
// Result: a 50/50 change on returning true of false

2. 检查指定日期是不是工做日

咱们能够经过此方法来检查函数中提供的日期是工做日仍是周末。学习

如下JS代码块显示了如何编写一个返回指定日期是工做日仍是周末的函数。spa

const isWeekday = (date) => date.getDay() % 6 !== 0;
console.log(isWeekday(new Date(2021, 0, 11)));
// Result: true (Monday)
console.log(isWeekday(new Date(2021, 0, 10)));
// Result: false (Sunday)

3. 反转字符串

有两种不一样的方式能够反转字符串。使用split()reverse()join()方法是最简单的方法之一。插件

如下JS代码块显示了如何反转字符串。code

const reverse = str => str.split('').reverse().join('');
reverse('hello world');     
// Result: 'dlrow olleh'

4. 检查当前tab是否在视图/焦点中

咱们可使用document.hidden属性来检查当前tab是否在视图/焦点中。

如下JS代码块显示了如何使用文档的hidden属性来获取当前tab是否在视图/焦点中。

const isBrowserTabInView = () => document.hidden;
isBrowserTabInView();
// Result: returns true or false depending on if tab is in view / focus

5. 检查数字是偶数仍是奇数

能够经过使用取模运算符(%)来解决这个超简单的任务。若是你对此还不太熟悉,那么Stack Overflow上就有直观的说明。

如下JS代码块显示了如何使用模运算符来检查数字是偶数仍是奇数。

const isEven = num => num % 2 === 0;
console.log(isEven(2));
// Result: true
console.log(isEven(3));
// Result: false

6. 从日期中获取时间

经过使用.toTimeString()方法并在合适的位置切割字符串,咱们就能够从指定的日期中获取时间,也能够获取当前时间。

如下JS代码块显示了如何经过toTimeString方法和切割字符串从日期中获取时间。

const timeFromDate = date => date.toTimeString().slice(0, 8);
console.log(timeFromDate(new Date(2021, 0, 10, 17, 30, 0))); 
// Result: "17:30:00"
console.log(timeFromDate(new Date()));
// Result: will log the current time

7. 截取数字小数点后的固定几位

使用Math.pow()方法,能够截取数字小数点后的固定几位。

如下JS代码块显示了如何使用Math.Power方法舍入某个小数点。

const toFixed = (n, fixed) => ~~(Math.pow(10, fixed) * n) / Math.pow(10, fixed);
// Examples
toFixed(25.198726354, 1);       // 25.1
toFixed(25.198726354, 2);       // 25.19
toFixed(25.198726354, 3);       // 25.198
toFixed(25.198726354, 4);       // 25.1987
toFixed(25.198726354, 5);       // 25.19872
toFixed(25.198726354, 6);       // 25.198726

8. 检查元素当前是否处于焦点

咱们可使用document.activeElement属性来检查一个元素当前是否处于焦点。

如下JS代码块显示了如何使用文档对象上的activeElement属性检查元素当前是否处于焦点。

const elementIsInFocus = (el) => (el === document.activeElement);
elementIsInFocus(anyElement)
// Result: will return true if in focus, false if not in focus

9. 检查当前用户是否支持touch事件

如下JS代码块显示了如何检查当前用户是否支持touch事件。

const touchSupported = () => {
  ('ontouchstart' in window || window.DocumentTouch && document instanceof window.DocumentTouch);
}
console.log(touchSupported());
// Result: will return true if touch events are supported, false if not

10. 检查当前用户是否使用Apple上

可使用navigator.platform来检查当前用户是否使用Apple设备。

如下JS代码块显示了如何检查用户当前是否在Apple设备上。

const isAppleDevice = /Mac|iPod|iPhone|iPad/.test(navigator.platform);
console.log(isAppleDevice);
// Result: will return true if user is on an Apple device

11. 滚动到页面顶部

window.scrollTo()方法经过x坐标和y坐标实现滚动。若是将它们设置为0,则将滚动到页面顶部。

注意:Internet Explorer不支持.scrollTo()方法。

如下JS代码块显示了如何使用scrollTo方法将浏览器滚动至顶部。

const goToTop = () => window.scrollTo(0, 0);
goToTop();
// Result: will scroll the browser to the top of the page

12. 获取参数的平均值

可使用reduce方法获取函数参数的平均值。

如下JS代码块显示了如何使用reduce方法获取参数的平均值。

const average = (...args) => args.reduce((a, b) => a + b) / args.length;
average(1, 2, 3, 4);
// Result: 2.5

13. 转换华氏/摄氏

最后一个2合1了!

处理温度有时会晕头转向。这两个函数则能帮助你们将华氏温度转换为摄氏温度,以及将摄氏温度转换为华氏温度。

如下JS代码块显示了如何将华氏温度转换为摄氏温度,以及反向的转换。

const celsiusToFahrenheit = (celsius) => celsius * 9/5 + 32;
const fahrenheitToCelsius = (fahrenheit) => (fahrenheit - 32) * 5/9;
// Examples
celsiusToFahrenheit(15);    // 59
celsiusToFahrenheit(0);     // 32
celsiusToFahrenheit(-20);   // -4
fahrenheitToCelsius(59);    // 15
fahrenheitToCelsius(32);    // 0

文本完,感谢阅读!

 

每日分享前端插件和前端开发教程,欢迎扫码关注个人公众号:前端新世界

相关文章
相关标签/搜索