目录
find:查找数组中符合条件的第一个元素,如果没有符合条件的元素,则返回undefined
部分方法复制于:20 个 JS 工具函数助力高效开发
reduce
举例:数组求和
-
let a=[1,3,6,5,7]; let init=0;//累加的初始值,默认为0,可不写 let b=a.reduce((pre,cur,index,arr)=>{ console.log('当前要加序号:',index); console.log('之前累加:',pre); console.log('当前要加:',cur); console.log('原始属组:',arr); console.log('---------'); return pre+cur;//必须要有返回值,否则循环走到第二步的时候,pre=undefined },init)//这里的init可以省略 console.log('全部累加:',b)
参数解析:
- pre:必填,表示上一次累加求和的返回值;
若存在init,则初始值=init;
若不存在init,则初始值=a[0] - cur:必填,表示当前要累加的数组元素;
- index:可选,表示当前要累加的数组元素下标;
若存在init,则index初始值=0;
若不存在init,则index初始值=1; - arr:可选,表示当前要处理的原始数组;
- init:可选,表示累加的初始值。
实现效果如下图:
at:获取数组指定位置的数据
const array = [ 'fatfish', 'medium', 'blog', 'fat', 'fish' ]
console.log(array.at(-1));//fish
console.log(array.at(-2));//fat
console.log(array.at(-3));//blog
console.log(array.at(-0));//fafish
console.log(array.at(1));//medium
typeOf:校验数据类型
export const typeOf = function(obj) {
return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase()
}
使用:typeOf(123);//number
手机号脱敏:
export const hideMobile = (mobile) => {
return mobile.replace(/^(\d{3})\d{4}(\d{4})$/, "$1****$2")
}
使用:hideMobile('18012345678'); //180****5678
显示全屏:
export const launchFullscreen = (element) => {
if (element.requestFullscreen) {
element.requestFullscreen()
} else if (element.mozRequestFullScreen) {
element.mozRequestFullScreen()
} else if (element.msRequestFullscreen) {
element.msRequestFullscreen()
} else if (element.webkitRequestFullscreen) {
element.webkitRequestFullScreen()
}
}
关闭全屏:
export const exitFullscreen = () => {
if (document.exitFullscreen) {
document.exitFullscreen()
} else if (document.msExitFullscreen) {
document.msExitFullscreen()
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen()
} else if (document.webkitExitFullscreen) {
document.webkitExitFullscreen()
}
}
大小写转换:
export const turnCase = (str, type) => {
switch (type) {
case 1:
return str.toUpperCase()
case 2:
return str.toLowerCase()
case 3:
//return str[0].toUpperCase() + str.substr(1).toLowerCase() // substr 已不推荐使用
return str[0].toUpperCase() + str.substring(1).toLowerCase()
default:
return str
}
}
str: 待转换的字符串
type :1-全大写 2-全小写 3-首字母大写
使用:
- turnCase('vue',1);//VUE
- turnCase('Vue',2);//vue
- turnCase('vue',3);//Vue
解析URL参数:
export const getSearchParams = () => {
const searchPar = new URLSearchParams(window.location.search)
const paramsObj = {}
for (const [key, value] of searchPar.entries()) {
paramsObj[key] = value
}
return paramsObj
}
使用:getSearchParams();//假如当前地址栏链接为https://****.com?a=1,此处输入{a:1}
判断手机是安卓还是iOS:
export const getOSType=() => {
let u = navigator.userAgent, app = navigator.appVersion;
let isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1;
let isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
if (isIOS) {
return 1;
}
if (isAndroid) {
return 2;
}
return 3;
}
数组对象根据字段去重:
export const uniqueArrayObject = (arr = [], key = 'id') => {
if (arr.length === 0) return
let list = []
const map = {}
arr.forEach((item) => {
if (!map[item[key]]) {
map[item[key]] = item
}
})
list = Object.values(map)
return list
}
使用:
假设
let a=[{id:1,text:'this is a'},{id:2,text:'this is b'},{id:3,text:'this is c'},{id:1,text:'this is aa'},
{id:2,text:'this is bb'},{id:3,text:'this is cc'}]
uniqueArrayObject(a,'id');//[{id:1,text:'this is a'},{id:2,text:'this is b'},{id:3,text:'this is c'}]
滚动到页面顶部or 底部:
export const scrollToTop = () => {
const height = document.documentElement.scrollTop || document.body.scrollTop;
if (height > 0) {
window.requestAnimationFrame(scrollToTop);
window.scrollTo(0, height - height / 8);
}
}
// or
export const goToTop = () => window.scrollTo(0,0, "smooth");
// or
// export const scrollToTop = (element) => element.scrollIntoView({behavior: "smooth", block: "start"});
// scroll to bottom of the page
export const scrollToBottom = () => window.scrollTo(0, document.body.scrollHeight);
滚动到指定元素为止:
export const smoothScroll = element =>{
document.querySelector(element).scrollIntoView({
behavior: 'smooth'
});
};
使用:smoothScroll('#app');
金额格式化:
export const moneyFormat = (number, decimals, dec_point, thousands_sep) => {
number = (number + '').replace(/[^0-9+-Ee.]/g, '')
const n = !isFinite(+number) ? 0 : +number
const prec = !isFinite(+decimals) ? 2 : Math.abs(decimals)
const sep = typeof thousands_sep === 'undefined' ? ',' : thousands_sep
const dec = typeof dec_point === 'undefined' ? '.' : dec_point
let s = ''
const toFixedFix = function(n, prec) {
const k = Math.pow(10, prec)
return '' + Math.ceil(n * k) / k
}
s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.')
const re = /(-?\d+)(\d{3})/
while (re.test(s[0])) {
s[0] = s[0].replace(re, '$1' + sep + '$2')
}
if ((s[1] || '').length < prec) {
s[1] = s[1] || ''
s[1] += new Array(prec - s[1].length + 1).join('0')
}
return s.join(dec)
}
说明:
number:要格式化的数字
-
decimals:保留几位小数
-
dec_point:小数点符号
-
thousands_sep:千分位符号
-
使用:
-
moneyFormat(10000000) // 10,000,000.00
moneyFormat(10000000, 3, '.', '-') // 10-000-000.000
下载文件:
export const downloadFile = (api, params, fileName, type = 'get') => {
axios({
method: type,
url: api,
responseType: 'blob',
params: params
}).then((res) => {
let str = res.headers['content-disposition']
if (!res || !str) {
return
}
let suffix = ''
// 截取文件名和文件类型
if (str.lastIndexOf('.')) {
fileName ? '' : fileName = decodeURI(str.substring(str.indexOf('=') + 1, str.lastIndexOf('.')))
suffix = str.substring(str.lastIndexOf('.'), str.length)
}
// 如果支持微软的文件下载方式(ie10+浏览器)
if (window.navigator.msSaveBlob) {
try {
const blobObject = new Blob([res.data]);
window.navigator.msSaveBlob(blobObject, fileName + suffix);
} catch (e) {
console.log(e);
}
} else {
// 其他浏览器
let url = window.URL.createObjectURL(res.data)
let link = document.createElement('a')
link.style.display = 'none'
link.href = url
link.setAttribute('download', fileName + suffix)
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
window.URL.revokeObjectURL(link.href);
}
}).catch((err) => {
console.log(err.message);
})
}
使用:downloadFile('/api/download', {params}, '文件名')
模糊搜索:
export const fuzzyQuery = (list, keyWord, attribute = 'name') => {
const reg = new RegExp(keyWord)
const arr = []
for (let i = 0; i < list.length; i++) {
if (reg.test(list[i][attribute])) {
arr.push(list[i])
}
}
return arr
}
说明:
-
list 原数组
-
keyWord 查询的关键词
-
attribute 数组需要检索属性
-
使用:
-
假如:
-
const list = [
{ id: 1, name: '树哥' },
{ id: 2, name: '黄老爷' },
{ id: 3, name: '张麻子' },
{ id: 4, name: '汤师爷' },
{ id: 5, name: '胡万' },
{ id: 6, name: '花姐' },
{ id: 7, name: '小梅' }
]
fuzzyQuery(list, '树', 'name') // [{id: 1, name: '树哥'}]
sort:对无序数组进行排序,会改变原始数组
可排序数字,字母;
let a=[1,56,3,78];
a.sort();
console.log(a);//[1,3,56,78]
includes:检查某值是否存在于元素中
let a=[1,56,3,78];
console.log(a.includes(3));//true
let b='ad43';
console.log(b.includes(3));//true
console.log(b.includes(5));//false
filter:过滤数组,返回一个新的数组,不改变原数组
let a=[1,56,3,78];
let b=a.filter((curValue,index,arr)=>{
console.log(curValue,index,arr);
return curValue ==1
})
console.log(b)
输出的值,如下图:
参数解析:
curValue:当前元素的值,必填;
index:当前元素序号,非必填;
arr:原始数组,非必填;
find:查找数组中符合条件的第一个元素,如果没有符合条件的元素,则返回undefined
let a=[1,56,3,78];
let b=a.find((e,i,arr)=>{
console.log(e,i,arr);
return e==3;//查找到e==3之后,后边的元素将不会继续调用
})
console.log(b)
返回结果如下图:
indexOf:查找指定值的索引
let a=[1,56,3,78];
console.log(a.indexOf(56));//56
let b='12356321';
console.log(b.indexOf(56));//3
join:数组转化为字符串
let a=[1,56,3,78];
console.log(a.join(','));//1,56,3,78
new Set():数组去重
const setArray = arr => [...new Set(arr)];
const arr = [1,2,3,4,5,1,3,4,5,2,6];
setArray(arr);//[1, 2, 3, 4, 5, 6]
扩展:利用new Set取两个数组的并集,交集与差集
let a=[1,2,4,5];
let b=[2,4,6,8];
//并集
let uni=new Set([...a,...b]);//[1,2,3,5,6,8];
//交集
let con=new Set([...a].filter(x=>b.has(x)));//[2,4]
//差集
let diff=new Set([...a].filter(x=>!b.has(x)));//[1,5,6,8]
复制到粘贴板:
export const copyToClipboard = text => (navigator.clipboard?.writeText ?? Promise.reject)(text);