13个JavaScript一行代码技巧,提升开发效率与专业感

作者:小括号时间:2026-10-24 14:53:25浏览:153

本文整理了13个JavaScript一行代码技巧,涵盖随机布尔值、工作日判断、字符串反转、标签页状态检测、奇偶数检查、时间提取、小数保留、焦点元素检测、触摸事件支持、苹果设备识别、滚动至顶部、参数平均计算及温度转换等功能。这些简洁的代码片段不仅能提升开发效率,还能让代码看起来更专业。

1. 获取随机布尔值

该函数利用Math.random()方法返回一个布尔值(true 或者alse)。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是HTML5新增的API,使用时可能存在兼容性问题。


var hidden
if (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));
// true
console.log(isEven(3));
// false

6. 从日期对象中提取时间


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. 保留指定小数位数


const toFixed = (n, fixed) => ~~(Math.pow(10, fixed) * n) / Math.pow(10, fixed);
// 事例
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属性来检查某个元素当前是否处于焦点状态。


const elementIsInFocus = (el) => (el === document.activeElement);
elementIsInFocus(anyElement)
// 如果在焦点中返回true,如果不在焦点中返回 false

9. 检测浏览器是否支持触摸事件


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.5

13. 华氏度与摄氏度转换


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

至此,关于13个JavaScript一行程序,让你看起来像个专家的文章介绍完毕。如需了解更多JavaScript相关内容,请搜索本站历史文章或继续浏览相关文章。希望大家今后多多支持本站!

作者最新文章