常用的JS方法 一行代码实现

以下为博主自己整理的常用的并且可以一行实现的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>')) // 哈哈哈哈<呵呵呵

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值