本文章是从微信上看到的一篇文章,以后可能会用到。若有侵犯,请通知我,感谢大佬
1.随机生成布尔值
Math.random()会返回0到1之前随机的数字,因此可以利用是否大于0.5来判断
const randomBoolean = () => Math.random() >= 0.5;
2.反转字符串
const reverse = str =>str.split('').reverse().join('');
3.判断浏览器Tab 窗口是否为活动窗口
const isBrowserTabInView = () =>document.hidden;
4.获取日期对象的时间部分
日期对象的.toTimeString()方法可以获取时间格式的字符串,截取前面部分
const timeFromDate = data => data.toTimeString().slice(0,8);
5.数字截断小数位
如果需要截断浮点数的小数位(不是四舍五入)可以借助Math.pow()实现:
const toFixed = (n,fixed)=>~~(Math.pow(10,fixed)*n)/Math.pow(10,fixed);
//Examples
toFixed(26.28382368,1);//16.2
toFixed(26.28382368,2);//16.28
//支持四舍五入的方法
//number 为入参想要转换的值
function round2(number,fixed){
with(Math){
return round(number*pow(10,fixed))/pow(10,fixed);
}
}
6.判断DOM元素是否已获得焦点
const elementIsInFocus = (el) => (el === document.activeElement);
7.判断当前环境是否支持touch事件
const touchSupported = () => {
('ontouchstart' in window || window.DocumentTouch && document instanceof window.DocumentTouch);
}
会直接返回值布尔值
8.判断是否为Apple设备
//isAppleDevice 布尔值
const isAppleDevice = /Mac|iPod|iPhone|iPad/.test(navigator.platform);
9.滚动到页面顶部
window.scrollTo()方法接受x和y两个参数,用于指定滚动目标的位置,全设置 为0,可以回到页面顶部:注:IE不支持
window.scrollTo(0,0)
10.求平均值
const average = (...args) => args.reduce((a,b) => (a+b)/args.length)