个人收集
反转字符串
// 有许多反转字符串的方法,这里使用一种最简单的,使用了 split(),reverse() 和 join()
const reverse = str => str.split('').reverse().join('');
reverse('hello world');
// Result: 'dlrow olleh'
判断当前标签页是否为可视状态
// 浏览器可以打开很多标签页,下面 👇🏻 的代码段就是判断当前标签页是否是激活的标签页
const isBrowserTabInView = () => document.hidden;
isBrowserTabInView();
保留指定的小数位
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
检查指定元素是否处于聚焦状态
// 可以使用 document.activeElement 来判断元素是否处于聚焦状态
const elementIsInFocus = (el) => (el === document.activeElement);
elementIsInFocus(anyElement)
// Result: 如果处于焦点状态会返回 True 否则返回 False
检查当前用户是否是苹果设备
// 可以使用 navigator.platform 判断当前用户是否是苹果设备
const isAppleDevice = /Mac|iPod|iPhone|iPad/.test(navigator.platform);
console.log(isAppleDevice);
// Result: 是苹果设备会返回 True
滚动至页面顶部
const goToTop = () => window.scrollTo(0, 0);
goToTop();
// Result: 将会滚动至顶部
获取所有参数的平均值
const average = (...args) => args.reduce((a, b) => a + b) / args.length;
average(1, 2, 3, 4);
// Result: 2.5