js单行代码记录

54 阅读1分钟

1.数组去重

const uniqueArr = (arr) => [...new Set(arr)];

2.从url获取参数并转为对象

const getParameters = URL => JSON.parse(`{"${decodeURI(URL.split("?")[1]).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"')}"}`)

3.检测对象是否为空

const isEmpty = obj => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object;  

4.反转字符串

const reverse = str => str.split('').reverse().join('');  

5.生成随机十六进制

const randomHexColor = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6"0")}` 

6.检查当前选项卡是否在后台

const isTabActive = () => !document.hidden

7.检测元素是否处于焦点(activeElement 属性返回文档中当前获得焦点的元素)

const elementIsInFocus = (el) => (el === document.activeElement); 

8.检测设备类型

const judgeDeviceType = ( ) =>/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|OperaMini/i.test(navigator.userAgent) ? 'Mobile' : 'PC';  

9.文字复制到剪贴板

const copyText = async (text) => await navigator.clipboard.writeText(text)  

10.获取选定的文本

const getSelectedText = ( ) => window.getSelection().toString( );  

11.查询某天是否为工作日

const isWeekday = (date) => date.getDay() % 6 !== 0;  
        eg:isWeekday(new Date(20220311))  

12.将华氏温度转换为摄氏温度

const fahrenheitToCelsius = (fahrenheit) => (fahrenheit - 32) * 5/9;  

13.将摄氏温度转华氏温度

const celsiusToFahrenheit = (celsius) => celsius * 9/5 + 32;  

14.两日期之间相差的天数

const dayDiff = (date1, date2) => Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000); 

15.将 RGB 转换为十六进制

const rgbToHex = (r, g, b) =>   "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1); 

16.计算数组平均值

const average = (arr) => arr.reduce((a, b) => a + b) / arr.length;