广州市|广州蓝景分享—前端新手入门, 13个JavaScript代码技巧, 让你看起来像个专业高手

广州市|广州蓝景分享—前端新手入门, 13个JavaScript代码技巧, 让你看起来像个专业高手

其实Javascript可以做很多神奇的事情 , 还有很多东西要学 。 今天广州蓝景介绍13个简短的代码帮助大家在开发过程中 , 写更少的代码 , 来实现更好、更强的功能 。

1、获取随机布尔值(真/假)
使用 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 0 11)));
// Result: true (Monday)
console.log(isWeekday(new Date(2021 0 10)));
// Result: false (Sunday)
3、反转字符串
反转字符串的方法有很多 , 这里是最简单的一种 , 使用 split()、reverse() 和 join()
const reverse = str => str.split(‘’).reverse().join(‘’);
reverse(‘hello world’);
// Result:’dlrow olleh’
4、判断当前标签是否可见
浏览器可以打开很多标签 , 下面的代码片段是判断当前标签是否为活动标签 。
const isBrowserTabInView = () => document.hidden;
isBrowserTabInView();
5、判断数字是奇数还是偶数
模数运算符 % 可以很好地完成这个任务 。
const isEven = num => num% 2 === 0;
console.log(isEven(2));
// Result: true
console.log(isEven(3));
// Result: false
6、从Date对象中获取时间
使用Date对象的.toTimeString()方法转换为时间字符串 , 然后截取该字符串 。
【广州市|广州蓝景分享—前端新手入门, 13个JavaScript代码技巧, 让你看起来像个专业高手】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: return the current time
7、保留指定的小数位
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 来确定元素是否处于焦点中 。
const elementIsInFocus = (el) => (el === document.activeElement);
elementIsInFocus(anyElement)
// Result: If it is in focus it will return True otherwise it will return False
9、检查当前用户是否支持触摸事件
const touchSupported = () => {
(‘ontouchstart’ in window ||
window.DocumentTouch && document instanceof window.DocumentTouch);

console.log(touchSupported());
// Result: If touch event is supported it will return True otherwise it will return False
10、检查当前用户是否为苹果设备
可以使用 navigator.platform 来判断当前用户是否是苹果设备 。
const isAppleDevice = /Mac|iPod|iPhone|iPad/.test(navigator.platform);
console.log(isAppleDevice);
// Result: Apple device will return True
11、滚动到页面顶部
window.scrollTo() 会滚动到指定坐标 , 如果坐标设置为(0 0) , 会返回到页面顶部 。
const goToTop = () => window.scrollTo(0 0);
goToTop();
// Result: will scroll to the top
12、获取所有参数的平均值
您可以使用 reduce() 函数计算所有参数的平均值 。
const average = (…args) => args.reduce((a b) => a + b) / args.length;