反转字符串
代码片
.
const reverse = str => str.split('').reverse().join('');
reverse('my name');
// 结果: 'eman ym'
当前 tab 页是否在前台
当前 Tab 页是否在前台 代码片
.
const isBrowserTabInView = () => document.hidden;
isBrowserTabInView();
// 结果: true or false
保留小数点(非四舍五入)
使用 ==Math.pow() ==方法,可以将一个数字截断到某个小数点。 代码片
.
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
浏览器是否支持触摸事件
代码片
.
const touchSupported = () => {
('ontouchstart' in window || window.DocumentTouch && document instanceof window.DocumentTouch);
}
console.log(touchSupported());
// 结果: 支持或不支持: true or false
当前用户是否为苹果设备
使用 navigator.platform来检查当前用户是否为苹果设备。 代码片
.
const isAppleDevice = /Mac|iPod|iPhone|iPad/.test(navigator.platform);
console.log(isAppleDevice);
// 结果: 支持或不支持: true or false
滚动到页面顶部
window.scrollTo() 方法会取一个 x 和 y 坐标来进行滚动。如果我们将这些坐标设置为零,就可以滚动到页面的顶部。 代码片
.
const goToTop = () => window.scrollTo(0, 0);
goToTop();
获取所有参数平均值
使用== reduce== 方法来获得函数参数的平均值。 代码片
.
const average = (...args) => args.reduce((a, b) => a + b) / args.length;
average(1, 2, 3, 4);
// 结果: 2.5