2022招聘季|前端工作中需要掌握的 15 个函数
source link: https://segmentfault.com/a/1190000041628824
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
随机排列数组
使用 sort
和 random
方法对数组进行乱序排列非常常用。
const shuffleArray = (arr) => arr.sort(() => 0.5 - Math.random()); console.log(shuffleArray([1, 2, 3, 4])); // 结果:[ 1, 4, 3, 2 ]
检查日期是否有效
使用以下代码段检查给定的日期是否有效。
const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf()); isDateValid("December 17, 1995 03:24:00"); // 结果:真
复制到剪贴板
将任何文本复制到剪贴板 navigator.clipboard.writeText
。
const copyToClipboard = (text) => navigator.clipboard.writeText(text); copyToClipboard("Hello World");
查找一年中的哪一天
查找给定日期的哪一天。
const dayOfYear = (date) => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24); dayOfYear(new Date()); // 结果:272
大写字符串
Javascript
没有内置的大写函数,所以我们可以使用以下代码处理。
const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1) capitalize("hello") // 结果:Hello
求两天之间的天数
使用以下代码段查找 2 天之间的天数。
const dayDif = (date1, date2) => Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000) dayDif(new Date("2020-10-21"), new Date("2021-10-22")) // 结果:366
清除所有 Cookie
可以通过 document.cookie
获取并清除 cookie
来轻松清除存储在网页上的所有 cookie
。
const clearCookies = document.cookie.split(';').forEach(cookie => document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, `=;expires=$ {new Date(0).toUTCString()};path=/`));
生成随机十六进制
可以使用 Math.random
和 padEnd
属性生成随机十六进制颜色。
const randomHex = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`; console.log(randomHex()); // 结果:#92b008
从数组中删除重复项
可以使用 Set
轻松删除重复项。
const removeDuplicates = (arr) => [...new Set(arr)]; console.log(removeDuplicates([1, 2, 3, 3, 4, 4, 5, 5, 6])); // 结果:[ 1, 2, 3, 4, 5, 6 ]
从 URL 获取查询参数
可以绕过 window.location
或原始 URL
,从 URL
中轻松检索查询参数 goole.com?search=easy&page=3
const getParameters = (URL) => { URL = JSON.parse('{"' + decodeURI(URL.split("?")[1]).replace(/"/g, '\\"').replace (/&/g, '","').replace(/=/g, '":"') +'"}'); 返回 JSON.stringify(URL); }; getParameters(window.location) // 结果:{ search : "easy", page : 3 }
从日期记录时间
我们可以用 hour::minutes::seconds
做给定日期的格式记录时间。
const timeFromDate = date => date.toTimeString().slice(0, 8); console.log(timeFromDate(new Date(2021, 0, 10, 17, 30, 0))); // 结果:“17:30:00”
检查一个数字是偶数还是奇数
const isEven = num => num % 2 === 0; console.log(isEven(2)); // 结果:真
求数字的平均值
reduce
使用方法找到多个数字之间的平均值。
const average = (...args) => args.reduce((a, b) => a + b) / args.length; average(1, 2, 3, 4); // 结果:2.5
检查数组是否为空
一个简单的函数检查数组是否为空,将返回 true
或者 false
。
const isNotEmpty = arr => Array.isArray(arr) && arr.length > 0; isNotEmpty([1, 2, 3]); // 结果:真
获取选定的文本
getSelection
使用内置属性获取用户选择的文本。
const getSelectedText = () => window.getSelection().toString(); getSelectedText();
检测是否处于暗模式
使用以下代码检查用户的设备是否处于暗模式。
const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches console.log(isDarkMode); // 结果:真或假
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK