持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第6天,点击查看活动详情
1. 数组去重
const duemovalArr = (arr) => [...new Set(arr)];
console.log(uniqueArr(["前端","Vue","html","Vue","css","html"]));
// ['前端', 'Vue', 'html', 'css']
duemovalArr方法将数据转为Set,然后再解构为数组返回。
2. 手机号脱敏
export const hideMobile = (mobile) => {
return mobile.replace(/^(\d{3})\d{4}(\d{4})$/, "$1****$2")
}
console.log(hideMobile('13121212324']));
// 131****2324
3. 校验数据类型
export const typeOf = function(obj) {
return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase()
}
示例:
typeOf('lol') // string
typeOf([]) // array
typeOf(new Date()) // date
typeOf(null) // null
typeOf(true) // boolean
typeOf(() => { }) // function
4. 从url获取参数并转为对象
网页路径经常是:www.baidu.com?search=js&xxx=kkk这种形式的,我们是经常需要取参数的,可以使用第三方的qs包实现,如果你只是要实现取参数,这一句代码就可以实现,不用再引入qs了。
第一种:
const getParameters = URL => JSON.parse(`{"${decodeURI(URL.split("?")[1]).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"')}"}`
)
getParameters("https://www.google.com.hk/search?q=js+md&newwindow=1");
// {q: 'js+md', newwindow: '1'}
第二种:
export const getSearchParams = () => {
const searchPar = new URLSearchParams(window.location.search)
const paramsObj = {}
for (const [key, value] of searchPar.entries()) {
paramsObj[key] = value
}
return paramsObj
}
// 假设目前位于 https://****com/index?id=132333&age=18;
getSearchParams(); // {id: "132333", age: "18"}
5. 检查对象是否为空
检查对象是否为空,实际上并不那么简单,即使对象为空,每次检查对象是否等于 {} 也会返回 false。
下面的单行代码正是我们想要的。
const isEmpty = obj => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object;
isEmpty({}) // true
isEmpty({a:"not empty"}) //false
6.反转字符串
反转字符串可以使用split结合reverse和join方法轻松实现。
const reverse = str => str.split('').reverse().join('');
reverse('this is reverse');
// esrever si siht
7. 计算数组平均值
const average = (arr) => arr.reduce((a, b) => a + b) / arr.length;
average([1,9,18,36]) //16
8. 数组对象根据字段去重
参数:
- arr 要去重的数组
- key 根据去重的字段名
export const uniqueArrayObject = (arr = [], key = 'id') => {
if (arr.length === 0) return
let list = []
const map = {}
arr.forEach((item) => {
if (!map[item[key]]) {
map[item[key]] = item
}
})
list = Object.values(map)
return list
}
示例:
const responseList = [
{ id: 1, name: '树哥' },
{ id: 2, name: '黄老爷' },
{ id: 3, name: '张麻子' },
{ id: 1, name: '黄老爷' },
{ id: 2, name: '张麻子' },
{ id: 3, name: '树哥' },
{ id: 1, name: '树哥' },
{ id: 2, name: '黄老爷' },
{ id: 3, name: '张麻子' },
]
uniqueArrayObject(responseList, 'id')
// [{ id: 1, name: '树哥' },{ id: 2, name: '黄老爷' },{ id: 3, name: '张麻子' }]
9. 大小写转换
参数:
- str 待转换的字符串
- type 1-全大写 2-全小写 3-首字母大写
export const turnCase = (str, type) => {
switch (type) {
case 1:
return str.toUpperCase()
case 2:
return str.toLowerCase()
case 3:
//return str[0].toUpperCase() + str.substr(1).toLowerCase() // substr 已不推荐使用
return str[0].toUpperCase() + str.substring(1).toLowerCase()
default:
return str
}
}
示例:
turnCase('vue', 1) // VUE
turnCase('REACT', 2) // react
turnCase('vue', 3) // Vue
10. 两日期之间相差的天数
日常开发中经常遇到需要显示剩余天数, 一般我们就需要计算两日期之间相差天数:
const dayDiff = (date1, date2) => Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000);
dayDiff(new Date("2021-10-21"), new Date("2022-02-12"))
// Result: 114
11. 查询某天是否为工作日
我们自己写日历组件时经常会用到,判断某个日期是否为工作日;周一至周五为工作日:
const isWeekday = (date) => date.getDay() % 6 !== 0;
isWeekday(new Date(2022, 03, 11))
// true
12. 获取选定的文本
使用内置的 getSelection 获取用户选择的文本:
const getSelectedText = () => window.getSelection().toString();
getSelectedText();
// 返回选中的内容**
13. 文字复制到剪贴板
Clipboard API 它的所有操作都是异步的,返回 Promise 对象,不会造成页面卡顿。而且,它可以将任意内容(比如图片)放入剪贴板。
const copyText = async (text) => await navigator.clipboard.writeText(text)
copyText('万事胜意,平安喜乐')
14. 生成随机十六进制
生成随机数相信你能信手拈来,那随机生成十六进制,例如生成十六进制颜色值。
const randomHexColor = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`
console.log(randomHexColor());
// #a2ce5b
15. 检测元素是否处于焦点
activeElement 属性返回文档中当前获得焦点的元素。
const elementIsInFocus = (el) => (el === document.activeElement);
elementIsInFocus(anyElement)
// 元素处于焦点返回true,反之返回false
16. 检查设备类型
使用navigator.userAgent 判断是移动设备还是电脑设备:
const judgeDeviceType =
() => /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|OperaMini/i.test(navigator.userAgent) ? 'Mobile' : 'PC';
judgeDeviceType() // PC | Mobile
17. 开启全屏
export const launchFullscreen = (element) => {
if (element.requestFullscreen) {
element.requestFullscreen()
} else if (element.mozRequestFullScreen) {
element.mozRequestFullScreen()
} else if (element.msRequestFullscreen) {
element.msRequestFullscreen()
} else if (element.webkitRequestFullscreen) {
element.webkitRequestFullScreen()
}
}
18. 关闭全屏
export const exitFullscreen = () => {
if (document.exitFullscreen) {
document.exitFullscreen()
} else if (document.msExitFullscreen) {
document.msExitFullscreen()
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen()
} else if (document.webkitExitFullscreen) {
document.webkitExitFullscreen()
}
}