数组去重
从数组中删除反复元素,如何简略优雅的实现
const uniqueArr =(item)=> [... new Set(item)]
console.log(uniqueArr(arr))
从 url 获取参数并转为对象
const getParameter = URL => JSON.parse(`{"${decodeURI(URL.split("?")[1])
.replace(/"/g,'\\"').replace(/&/g,'","').replace(/=/g,'":"')}"}`)
getParameter("http:''www.baidu.com/search?q=js+md&type=webpage")
//{q:"js+md",type:"webpage"}
检测对象是否为空
const isEmpty = obj => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object;
isEmpty({}) // true
isEmpty({1:'my name is empty'}) // false
十六进制随机色调
// 生成随机色
const randomColor = () =>`#${Math.floor(Math.random()* 0xffffff)
.toString(16).padEnd(6,'0')}`
console.log(randomColor())
查看以后选项卡是否在后盾
const isTabActive = () => !document.hidden
isTabActive() // true | false
查看设施类型
// 查看设施类型
const isMobileOrPc = () =>
/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|OperaMini/i.test(navigator.userAgent)
? 'Mobile' : 'PC';
### isMobileOrPc() // PC | Mobile
文字复制到剪贴板
// 文字复制到剪贴板
const copyText = async (text) => await navigator.clipboard.writeText(text)
copyText('13678933456')
获取选定文本
const getSelectText = () => window.getSelection.toString()
getSelectText()
判断某天是否为工作日
// 判断某天是否为工作日
const isWeekday = (date) => date.getDay() % 6 !== 0
isWeekday(new Date(2023,02,19)) // false
计算两个日期之间相差的天数
const dayDiff = (date1,date2) =>Math.ceil(Math.abs(date1.getTime() -date2.getTime()) / 86400000);
dayDiff(new Date(2023,02,19),new Date(2022,06,28))
计算平均数
const average = (arr) => arr.reduce((a,b)=> a+b)/arr.length
average([4,8,13,45])
//17.5