以下为博主自己整理的常用的并且可以一行实现的js代码,不定时更新,让你的代码看起来更加高大上一些(坏笑 ~_~ )
1、生成随机颜色
const randomHex = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`;
2、数组乱序
const shuffleArray = (arr) => arr.sort(() => Math.random() - 0.5)
3、数组去重
const getUnique = (arr) => [...new Set(arr)]
4、滚动到顶部
const scrollToTop = (element) =>
element.scrollIntoView({ behavior: "smooth", block: "start" })
5、滚动到底部
const scrollToBottom = (element) =>
element.scrollIntoView({ behavior: "smooth", block: "end" })。
6、获取浏览器Cookie的值
const cookie = name => `; ${document.cookie}`.split(`; ${name}=`).pop().split(';').shift();
cookie('_ga');
7、复制到剪贴板
const copyToClipboard = (text) => navigator.clipboard.writeText(text);
copyToClipboard("Hello World");
8、清除全部Cookie
const clearCookies = document.cookie.split(';').forEach(cookie => document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date(0).toUTCString()};path=/`));
9、从 URL 获取查询参数
Object.fromEntries(new URLSearchParams(window.location.search))
10、翻转字符串
const reverse = str => str.split('').reverse().join('');
reverse('hello world');
11、校验数组是否为空
const isNotEmpty = arr => Array.isArray(arr) && arr.length > 0;
12、计算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"))
13、提取A数组中B数组存在的元素
this.menuList = routes.filter(e => {
return menuNm.some(item => item == e.name)
})
14、判断函数是否为Promise函数
export const isPromise = (str:any) => Object.prototype.toString.call(str) === '[object Promise]'
15、去除空格
// 去除前后空格
export const empty = (str: string) => str.replace(/^\s+|\s+$/g, '');
// 去除所有空格
export const emptyAll = (str: string) => str.replace(/\s/g, '');
16、输入一个值,将其返回数据类型
function typego(para) {
return Object.prototype.toString.call(para)
}
17、验证邮箱的正则表达式
function isEmail(sEmail) {
var reg = /^([\w+\.])+@\w+([.]\w+)+$/
return reg.test(sEmail)
18、去除字符串中的html代码
const removehtml = (str = '') => str.replace(/<[/!]*[^<>]*>/ig, '')
console.log(removehtml('<h1>哈哈哈哈<呵呵呵</h1>')) // 哈哈哈哈<呵呵呵