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

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.hiddenh5新增加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. 保留 n 位小数

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.华氏/摄氏转换

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值