JavaScript小技巧

103 阅读3分钟

JavaScript小技巧,让你的代码更优雅

1.数组去重

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

console.log(uniqueArr(["前端","js","html","js","css","html"]));
// ['前端,'js','html','css']

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

  • 方式1
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'}
  • 方式2
const paramsString1 = "http://example.com/search?query=%40";

const searchParams = new URLSearchParams(paramsString);

searchParams.get('query') 
// %40

3.反转字符串

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

reverse('this is reverse');
// esrever si siht

4.生成随机十六进制

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

console.log(randomHexColor());
// #a2ce5b

5.检测元素是否处于焦点

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

elementIsInFocus(anyElement)\
// 元素处于焦点返回true,反之返回false

6.检查设备类型

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

judgeDeviceType() 
// PC | Mobile

7.文字复制到剪贴板

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

copyText('单行代码 前端世界')

8.获取选定的文本

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

getSelectedText();
// 返回选中的内容

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

我们自己写日历组件时经常会用到,判断某个日期是否为工作日;周一至周五为工作日:

const isWeekday = (date) => date.getDay() % 6 !== 0;

isWeekday(new Date(20220311))
// true

10.转换华氏/摄氏

  • 将华氏温度转换为摄氏温度
const fahrenheitToCelsius = (fahrenheit) => (fahrenheit - 32) * 5/9;

fahrenheitToCelsius(50);
// 10
  • 将摄氏温度转华氏温度
const celsiusToFahrenheit = (celsius) => celsius * 9/5 + 32;

celsiusToFahrenheit(100)
// 212

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

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

12.将 RGB 转换为十六进制

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

rgbToHex(255255255); 
//  #ffffff

13.将 RGBA 转换为十六进制

//转化颜色
function getHexColor(color) {
  const values = color
    .replace(/rgba?\(/, '')
    .replace(/\)/, '')
    .replace(/[\s+]/g, '')
    .split(',')
  const a = parseFloat(values[3] || 1),
    r = Math.floor(a * parseInt(values[0]) + (1 - a) * 255),
    g = Math.floor(a * parseInt(values[1]) + (1 - a) * 255),
    b = Math.floor(a * parseInt(values[2]) + (1 - a) * 255)
  return '#' +
    ('0' + r.toString(16)).slice(-2) +
    ('0' + g.toString(16)).slice(-2) +
    ('0' + b.toString(16)).slice(-2)
}

getHexColor('rgba(194, 7, 15, 1) '); 
// #c2070f

14.计算数组平均值

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

average([1,9,18,36])
// 16

15.滚动到顶部

const scrollToTop = (element) =>element.scrollIntoView({ behavior"smooth", block"start" })

16.滚动到底部

const scrollToBottom = (element) =>element.scrollIntoView({ behavior"smooth", block"end" })

17.监听浏览器窗口是否最大化

const browserFull = ()=>{  
let flag= window.outerHeight === screen.availHeight && window.outerWidth === screen.availWidth  
return flag  
}

18.强制等待

const sleep = async (t) => new Promise((resolve) => setTimeout(resolve, t));  
sleep(2000).then(() => {console.log('time')});

19.uuid

const uuid = (a) => (a ? (a ^ ((Math.random() * 16) >> (a / 4))).toString(16) : ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, uuid))  
uuid()

20.补零

const replenishZero = (num, len, zero = 0) => num.toString().padStart(len, zero)  
replenishZero(82// 08

21.判断日期是否为今天

const isToday = (date) => date.toISOString().slice(0, 10) === new Date().toISOString().slice(0, 10)

22.日期转换YYYY-MM-DD 格式

const formatYmd = (date) => date.toISOString().slice(010);  
formatYmd(new Date())

23.秒数转换

const formatSeconds = (s) => new Date(s * 1000).toISOString().substr(118)  
formatSeconds(200// 00:03:20

24.获取某年某月的第一天

const getFirstDate = (d = new Date()) => new Date(d.getFullYear(), d.getMonth(), 1);  
getFirstDate(new Date('2022-04')) // Fri Apr 01 2022 00:00:00 GMT+0800 (中国标准时间)

25.获取某年某月的最后一天

const getLastDate = (d = new Date()) => new Date(d.getFullYear(), d.getMonth() + 10);  
getLastDate(new Date('2023-03-04')) // Fri Mar 31 2023 00:00:00 GMT+0800 (中国标准时间)

25.获取某年月份天数

const getDaysNum = (year, month) => new Date(year, month, 0).getDate()    
const day = getDaysNum(20242// 29

26.生成数组

const createArr = (n) => Array.from(new Array(n), (v, i) => i)  
const arr = createArr(100// 0 - 99 数组

27.保留小数,四舍五入,移除多余的0

const myFixed = (num, digit) => {
	if (Object.is(parseFloat(num), NaN)) {
		return console.log(`传入的值:${num}不是一个数字`);
	}
	num = parseFloat(num);
	let fixedNo = (Math.round((num + Number.EPSILON) * Math.pow(10, digit)) / Math.pow(10, digit)).toFixed(digit);
	// 移除多余的0
	fixedNo = fixedNo.replace(/0+$/g, '').replace(/\.$/, '');
	return fixedNo;
};