计算平均数
const average = arr => arr.reduce((a, b) => a + b) / arr.length;
将 RGB 转为十六进制
const rgbToHex = (r, g, b) =>
'#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
计算两个日期相差的天数
const DayDiff = (firstDate, lastDate) =>
Math.ceil(Math.abs(firstDate.getTime() - lastDate.getTime()) /
1000 * 60 * 60 * 2
);
华氏度 / 摄氏度互相转换
# 华氏度转摄氏度
const fahrenheitToCelsius = item => ((item - 32) * 5) / 9;
# 摄氏度转华氏度
const celsiusToFahrenheit = item => (item * 9) / 5 + 32;
查问某个日期是否为工作日
const isWeekday = date => date.getDay() % 6 !== 0;
获取选定的文本
const getSelectedText = () => window.getSelection().toString();
文字复制到剪贴板
const copyText = async text => await navigator.clipboard.writeText(text);
查看设施类型
const judgeDeviceType = () =>
/Android|webOS|iPhone|iPad|BlackBerry|IEMobile|OperaMini/i.test(navigator.userAgent)
? 'Mobile'
: 'PC';
查看浏览器以后选项卡是否在后盾
const isTabActive = () => !document.hidden;
生成随机十六进制色彩值
const randomHexColor = () =>
`#${Math.floor(Math.random() * 0xfffffff)
.toString(16)
.padEnd(6, '0')}`;
反转字符串
const reverse = str => str.split(‘’).reverse().join(‘’);
从 url 地址获取参数并转为对象
const getParameters = URL =>
JSON.parse(`{"${decodeURI(URL.split('?')[1])
.replace(/"/g,'\\"')
.replace(/&/g, '","')
.replace(/=/g, '":"')}"}`
);
查看对象是否为空
const isEmpty = obj => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object;
多重条件判断优化
# 同一个值比照不同的值
# name 为被比照的值
if (name ===’tom’|| name ===‘doy’|| name ===‘daiwei') {// ...}
# 升高耦合性的写法
const nameArr = [’tom’,‘doy’,‘daiwei’];
if (nameArr.includes(name)) {// ...}
生成随机数
# 随机数最大值为 max, 最小值为 min
const getRandomNum = (min = 0, max = 10) => {return Math.floor(Math.random() * (max - min + 1)) + min;
};
前端搜寻
# arr 要搜寻的数组,text 要搜寻的内容
# 含糊搜寻
const result = (arr, text) => arr.filter(item => item === text);
# 准确搜寻
const result = (arr, text) => arr.find(item => item === text);