计算平均数

    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);

Tom_Li
26 声望2 粉丝

热爱学习,热爱总结,热爱广博知识