36个常用js
- 检测某个元素是否聚焦
consthasFocus = el => el === document.activeElement - 获取某个元素所有的兄弟元素
const a = el => [].slice.call(el.parentNode.children).filter(child => child !== el) - 获取当前选择的文本
const getSelectedText = () => window.getSelection().toString() - 获取所有 cookie 并转为对象
const getCookies = () => document.cookie .split(‘;’) .map(item => item.split(‘=’)) .reduce((acc, [k, v]) => (acc[k.trim().replace(‘"’, ‘’)] =v) && acc, {}) - 清除所有 cookie
const clearCookies = () => document.cookie .split(‘;’) .forEach(c =>document.cookie = c.splace(/^+/, ‘’) .replace(/=.*/,=;expires=${newDate().toUTCString()};path=/
)) ) - 将 URL 参数转换为对象
const getUrlParams = (query) =>Array.from(newURLSearchParams(query)).reduce((p, [k, v]) =>Object.assign({}, p, { [k]: p[k] ? (Array.isArray(p[k]) ? p[k] : [p[k]]).concat(v) : v }),{}); - 检测是否为暗模式
const isDarkMode = window.matchMedia && window.matchMedia(‘(prefers-color-scheme: dark)’).matches; - 比较两个数组
const isEqual = (a, b) => JSON.stringify(a) === JSON.stringify(b); - 将数组转为对象
const arrayToObject = (arr, key) => arr.reduce((a, b) => ({ …a, [b[key]]: b }), {}); - 将数组按照属性计数
const countBy = (arr, prop) => arr.reduce((prev, curr) => ((prev[curr[prop]] = ++prev[curr[prop]] || 1), prev), {} ); - 判断数组是否不为空
const arrayIsNotEmpty = (arr) => Array.isArray(arr) && Object.keys(arr).length > 0; - 展开多维数组
const flat_entries = arr => [].concat(…arr); - 获取数组最后一个元素
const lastItem = arr => arr.slice(-1)[0] - 检测多个对象是否相等
const isEqual = (…objects) => objects.every((obj) =>JSON.stringify(obj) === JSON.stringify(objects[0])); - 从对象数组中提取属性值
constpluck = (objs, property) => objs.map((obj) => obj[property]); - 反转对象的 key value
constinvert = (obj) => Object.keys(obj).reduce((res, k) =>Object.assign(res, { [obj[k]]: k }), {}); - 从对象中删除值为 null 和 undefined 的属性
constremoveNullAndUndefined = (obj) => Object.entries(obj) .reduce((a, [k, v]) => (v == null ? a : ((a[k] = v), a)), {}); - 按照对象的属性对对象排序
const sort = (obj) => Object .keys(obj) .sort() .reduce((p, c) => ((p[c] = obj[c]), p), {}); - 检测对象是否为 Promise
const isPromise = (obj) => !!obj && (typeof obj === ‘object’ || typeof obj === ‘function’) && typeof obj.then === ‘function’; - 检查路径是否是相对路径
const isRelative = (path) => !/^([az]+:)?[\/]/i.test(path); - 生成 IP 地址
const randomIp = () => Array(4).fill(0) .map((_, i) =>Math.floor(Math.random() * 255) + (i === 0 ? 1 : 0) ) .join(‘.’); - 生成十六进制颜色字符串
const randomColor = () =>#${Math.random().toString(16).slice(2, 8).padEnd(6, '0')}
; - 生成 rgb 颜色字符串
constrandomRgbColor = () =>rgb(${Math.floor(Math.random()*255)}, ${Math.floor(Math.random()*255)}, ${Math.floor(Math.random()*255)})
- 下划线转驼峰
const toHump = str => str.replace(/_(\w)/g, (all, letter) => letter.toUpperCase()); - 驼峰转下划线横线
const toLine = str => str.replace(/([A-Z])/g,“_$1”).toLowerCase() - 检查字符串是否是十六进制颜色
const isHexColor = (color) => /^#([0-9A-F]{3}|[0-9A-F]{4}|[0-9A-F]{6}|[0-9A-F]{8})$/i.test(color); - RGB 字符串转十六进制字符串
const rgbToHex = (r, g, b) => “#” + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1) ; - 两个日期之间相差的天数
const diffDays = (date, otherDate) => Math.ceil(Math.abs(date - otherDate) / (1000 * 60 * 60 * 24)); - 检查日期是否有效
const isDateValid = (…val) => !Number.isNaN(newDate(…val).valueOf()); - 检测代码是否处于 Node.js 环境
const isNode = typeof process !== ‘undefined’ && process.versions != null && process.versions.node != null; - 检测代码是否处于浏览器环境
const isBrowser = typeofwindow === ‘object’ && typeofdocument === ‘object’;