正在学习前端入门的爱好者,可以看过来,其实Javascript语言可以做很多神奇的事情,还有很多东西要学。今天广州蓝景简单跟大家介绍12个简短的代码帮助大家在开发过程中,写更少的代码,实现更好、更强的功能。
01、判断一个数是奇数还是偶数
模运算符 % 做得很好。
const IsEven = num => num % 2 === 0;
console.log(IsEven(2));
// Result: true
console.log(IsEven(3));
// Result: false
02、获取随机布尔值(真/假)
使用 Math.random() 会返回一个介于 0 和 1 之间的随机数,然后判断是否大于 0.5 会得到一个有 50% 概率为 True 或 False 的值。
const randomBool = () => Math.random() >= 0.5;
console.log(randomBool());
03、判断日期是否为工作日
检查给定日期是否为工作日。
const isWorkday = (date) => date.getDay() % 6 !== 0;
console.log(isWorkday(new Date("2022/10/17")));
// Result: true (Monday)
console.log(isWorkday(new Date("2022/10/16")));
// Result: false (Sumday)
04、从日期对象获取时间
使用 Date 对象的 .toTimeString() 方法将其转换为时间字符串,然后截取该字符串。
const timeBeginDate = date => date.toTimeString().slice(0, 8);
console.log(timeBeginDate(new Date(2022, 8, 10, 15, 30, 21)));
// Result: "15:30:21"
console.log(timeBeginDate(new Date()));
// Result: return current time
05、滚动到页面顶部
window.scrollTo() 会滚动到指定坐标,如果坐标设置为(0, 0),会返回到页面顶部。
const toTop = () => window.scrollTo(0, 0);
toTop();
06、反转字符串
反转字符串的方法有很多,这里是最简单的一种,使用 split()、reverse() 和 join()
const reverse = str => str.split('').reverse().join('');
console.log(reverse('hello maxwell'));
//Result: llewxam olleh
07、确定当前选项卡是否可见
浏览器可以打开很多标签,下面的代码段是判断当前标签是否为活动标签。
const isBrowserTabInView = () => document.hidden;
isBrowserTabInView();
08、检查指定元素是否被聚焦
你可以使用 document.activeElement 来确定元素是否处于焦点中。
const elementIsFocus = (el) => (el === document.activeElement);
elementIsFocus(anyElement)
// Returns True if it is in focus, otherwise returns False
09、判断当前用户是否支持触摸事件
const touchSupported = () => {
('ontouchstart' in window || window.DocumentTouch && document instanceof window.DocumentTouch);
}
console.log(touchSupported());
// Returns True if touch events are supported, otherwise returns False
10、判断当前用户是否为 Apple 设备
你可以使用 navigator.platform 来确定当前用户是否是 Apple 设备。
const isAppleDevice = /Mac|iPod|iPhone|iPad/.test(navigator.platform);
console.log(isAppleDevice);
// If it is an Apple device it will return True otherwise it will return False
11、获取所有参数的平均值
reduce() 函数可用于计算所有参数的平均值。
const average = (...args) => args.reduce((a, b) => a + b) / args.length;
var avg = average(6,10, 8, 12);
console.log(avg);
// Result: 9
12、转换华氏/摄氏度
不要再害怕处理温度单位了,下面两个函数就是两个温度单位的相互转换。
const celsiusToFahrenheit = (celsius) => celsius * 9 / 5 + 32;
const fahrenheitToCelsius = (fahrenheit) => (fahrenheit - 32) * 5 / 9;
// Examples
console.log(celsiusToFahrenheit(20)); // 68
console.log(celsiusToFahrenheit(0)); // 32
console.log(celsiusToFahrenheit(-15)); // 5
console.log(celsiusToFahrenheit(35)); // 95
如果有兴趣了解、对比,可以共同交流。