at:获取数组指定位置的数据

目录
at:获取数组指定位置的数据
:校验数据类型
手机号脱敏:
显示全屏:
关闭全屏:
大小写转换:
解析URL参数:
判断手机是安卓还是iOS:
数组对象根据字段去重:
滚动到页面顶部or 底部:
滚动到指定元素为止:
金额格式化:
下载文件:
模糊搜索:
sort:对无序数组进行排序 , 会改变原始数组
:检查某值是否存在于元素中
:过滤数组,返回一个新的数组,不改变原数组
find:查找数组中符合条件的第一个元素,如果没有符合条件的元素 , 则返回
:查找指定值的索引
join:数组转化为字符串
new Set():数组去重
复制到粘贴板:
部分方法复制于:20 个 JS 工具函数助力高效开发
举例:数组求和
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:获取数组指定位置的数据

文章插图
at:获取数组指定位置的数据
const array = [ 'fatfish', 'medium', 'blog', 'fat', 'fish' ]console.log(array.at(-1));//fishconsole.log(array.at(-2));//fatconsole.log(array.at(-3));//blogconsole.log(array.at(-0));//fafishconsole.log(array.at(1));//medium
:校验数据类型
export const typeOf = function(obj) {return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase()}
使用:(123);//
手机号脱敏:
export const hideMobile = (mobile) => {return mobile.replace(/^(\d{3})\d{4}(\d{4})$/, "$1****$2")}
使用:('');//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-首字母大写
使用:
解析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}
使用:();//假如当前地址栏链接为****.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) returnlet 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'}]
(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 exportconst goToTop = () => window.scrollTo(0,0, "smooth");// or// exportconst scrollToTop = (element) => element.scrollIntoView({behavior: "smooth", block: "start"});// scroll to bottom of the pageexport const scrollToBottom = () => window.scrollTo(0, document.body.scrollHeight);
滚动到指定元素为止:
export const smoothScroll = element =>{document.querySelector(element).scrollIntoView({behavior: 'smooth'});};
使用:('#app');
金额格式化:
at:获取数组指定位置的数据

文章插图
export const moneyFormat = (number, decimals, dec_point, thousands_sep) => {number = (number + '').replace(/[^0-9+-Ee.]/g, '')const n = !isFinite(+number) ? 0 : +numberconst prec = !isFinite(+decimals) ? 2 : Math.abs(decimals)const sep = typeof thousands_sep === 'undefined' ? ',' : thousands_sepconst dec = typeof dec_point === 'undefined' ? '.' : dec_pointlet 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)}
说明:
:要格式化的数字
下载文件:
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 = http://www.kingceram.com/post/urllink.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);})}
使用:('/api/',{},'文件名')???????
模糊搜索:
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}
说明:
sort:对无序数组进行排序,会改变原始数组
可排序数字,字母;
let a=[1,56,3,78];a.sort();console.log(a);//[1,3,56,78]
:检查某值是否存在于元素中
let a=[1,56,3,78];console.log(a.includes(3));//truelet b='ad43';console.log(b.includes(3));//trueconsole.log(b.includes(5));//false
:过滤数组 , 返回一个新的数组 , 不改变原数组
let a=[1,56,3,78];let b=a.filter((curValue,index,arr)=>{console.log(curValue,index,arr);return curValue =http://www.kingceram.com/post/=1})console.log(b)
输出的值,如下图:
参数解析:
:当前元素的值 , 必填;
index:当前元素序号 , 非必填;
arr:原始数组,非必填;
find:查找数组中符合条件的第一个元素,如果没有符合条件的元素,则返回
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)
返回结果如下图:
:查找指定值的索引
let a=[1,56,3,78];console.log(a.indexOf(56));//56let 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]
复制到粘贴板:
【at:获取数组指定位置的数据】export const copyToClipboard = text => (navigator.clipboard?.writeText ?? Promise.reject)(text);