这里博主趁着手上暂时还没有需求给小伙伴们分享一些实用的项目总结:放在全局封装成公用的方法或者局部使用都很合适。
1.数组排序
// 如果降序把( a-b )换成 ( b-a )
const setSorting = (arr)=>arr.sort((a,b)=>a-b)
console.log(setSorting([2,3,1,6,4])) // 1 2 3 4 6
2.数组过滤
// 把 (item > 2) 换成过滤条件就行
const setFilter = (arr)=>arr.filter(item =>item > 2)
console.log(setFilter([1,2,3,4,5])) // 3 4 5
3.计算两日期之间相差的天数
// 例: new Date("2022-10-21") 打印出来是 Fri Oct 21 2022 08:00:00 GMT+0800 (中国标准时间)
const dayDiff = (date1, date2) => Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000);
console.log(dayDiff(new Date("2022-10-21"), new Date("2022-12-12"))) // 52
4.检查用户是pc端 还是手机端
// 可以用于布置手机端电脑端两套代码
const judgeDeviceType =() => /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|OperaMini/i.test(navigator.userAgent) ? 'Mobile' : 'PC';
console.log(judgeDeviceType()) // PC | Mobile
5.检查对象是否为空
// 适用于对象检查 对象是否为{}
const isEmpty = obj => Object.keys(obj).length === 0 && JSON.stringify(obj) === '{}';
console.log(isEmpty({})) // true
6.获取Url传参
// 用来查询接口传值这些再合适不过了
const getParameters = URL => JSON.parse(`{"${decodeURI(URL.split("?")[1]).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"')}"}`)
console.log(getParameters("https://www.google.com.hk/search?q=js+md&newwindow=1")) //{q: 'js+md', newwindow: '1'}
7.数组去重
// 实现一行代码去重
const uniqueArr = (arr) => [...new Set(arr)];
console.log(uniqueArr([1,2,3,4,5,3,2])) // 1 2 3 4 5
8.根据对象里面的某个属性进行累加(获取累加和)
// 使用时把 'age' 属性换成要累加的属性就可以了
const calcCumulative = (arr)=>arr.reduce((x,y) => x + y?.age,0) // 10
calcCumulative([
{age:1},
{age:2},
{age:3},
{age:4}
])
9.检查数据类型
// 与typeof类似 但弥补了typeof 的不足之处
const checktestType =(str)=> Object.prototype.toString.call(str)
checktestType({}) // [object Object]
10.判断是不是数字
// 数字类型返回 false; 其它类型返回 true
const checkForNumbers = (e)=> e && e!==true?isNaN(e):true;
console.log(checkForNumbers('1')) // false
11.数组内容自动填充
// num是自动填充个数 val是自动填充类容
const automaticFilling = (num,val)=> Array(num).fill(val)
console.log(automaticFilling(3,'')) // ['', '', '']
12.字符串内容自动填充
// 字符串自动填充
const getFillStr = (str) => str.padStart(8,'0')
console.log(getFillStr('1234')) // 00001234 不传'0'默认补空字符串
13.设置sessionStorage
// 'data' 设置为获取数值的key 随便写但需要前后对应, '测试'是要设置的内容
sessionStorage.setItem('data','测试');
console.log(sessionStorage.getItem('data')) // 测试
14.设置主键唯一值
// 一般用于id赋值;赋值UUid
const getrandomGuid = () => Math.random().toString(36).slice(2);
console.log(getrandomGuid()) // 3ep8w7qndnq
15.设置uuid
// 一般用于id赋值;赋值UUid
const getrandomUuid = () => crypto.randomUUID();
console.log(getrandomGuid()) // '8283f9b9-d085-4461-9c66-45b0e47339b7'
16.设置uuid(原生)
const getUuid = function (len, radix) {
var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
var uuid = []
var i
radix = radix || chars.length
if (len) {
for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix]
} else {
var r
uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'
uuid[14] = '4'
for (i = 0; i < 36; i++) {
if (!uuid[i]) {
r = 0 | Math.random() * 16
uuid[i] = chars[(i === 19) ? (r & 0x3) | 0x8 : r]
}
}
}
return uuid.join('')
}
console.log(getUuid ()) //'FA267B53-B332-47D0-9A92-6E0817DE2465'
17.判断 a == 1 && a==2 && a==3
// 这个仅作了解使用,实际项目中用不到
let a ={
n : 1,
valueOf :function(){
return this.n ++;
}
}
console.log(a == 1 && a == 2 && a ==3) // true
18.动态获取电脑屏幕宽高以及盒子宽高
document.body.clientWidth/clientHeight // 获取电脑可视区域宽高
document.getBoundingClientRect().width/height // 获取单个盒子宽高,高兼容
19.滚动到页面顶部
const goToTop = () => window.scrollTo(0,0)
goToTop()
20.滚动到可视区域
const scrollToTop = (element) =>
element.scrollIntoView({behavior:'smooth',block:'start'})
scrollToTop(document.body)
21.后端返回文件流格式数据处理方法(application/octet-stream)
// data 为后端返回数据
let blob = new Blob([data], {
type: 'application/pdf'
});
let url = window.URL.createObjectURL(blob);
return url // url 就是你想要的url地址
22.修改滚动条样式
// 单独在某个盒子前面加 只需要在:: 前面加上 class类名就行了
::-webkit-scrollbar {
width: 10px;
height: 1px;
}
::-webkit-scrollbar-thumb {
//滑块部分
border-radius: 5px;
background-color: rgba(0, 0, 0, 0.15)
}
::-webkit-scrollbar-track {
//轨道部分
box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.1);
background: #ededed;
border-radius: 5px;
}
23.获取系统当前时间(YY-MM-DD hh:mm:ss)
const getNowFmatter = (date) =>
`${date.toISOString().slice(0,10)} ${date.toLocaleTimeString()}`
getNowFmatter(new Date()) // '2023-01-19 18:12:30'
24.判断是否是IE环境
const isIE = () => !!document.documentMode
25. 浏览器压力测试
// 1.打开F12浏览器控制台
// 2.输入 document.body.contentEditable = 'true' 敲回车
// 3.然后浏览器页面就可以像word文档一样编辑了,适合页面做压力测试
document.body.contentEditable = 'true'
总结:
以上就是今天要讲的内容,本文仅仅简单介绍了一些感觉工作中常用的方法;后续有感觉比较常用得方法会在这篇博客中持续更新;别划走,希望小伙伴们能点赞、收藏、关注一波,也是对小小的支持,非常感谢!