js的一些工具函数以及方法

阅读: 评论:0

js的一些工具函数以及方法

js的一些工具函数以及方法

 

目录

reduce

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

typeOf:校验数据类型

手机号脱敏:

显示全屏:

关闭全屏:

大小写转换: 

解析URL参数:

判断手机是安卓还是iOS:

数组对象根据字段去重:

滚动到页面顶部or 底部:

滚动到指定元素为止:

金额格式化:

下载文件:

模糊搜索:

sort:对无序数组进行排序,会改变原始数组

includes:检查某值是否存在于元素中

filter:过滤数组,返回一个新的数组,不改变原数组

find:查找数组中符合条件的第一个元素,如果没有符合条件的元素,则返回undefined

indexOf:查找指定值的索引

join:数组转化为字符串

new Set():数组去重

复制到粘贴板:


部分方法复制于:20 个 JS 工具函数助力高效开发

reduce

举例:数组求和

  1. let a=[1,3,6,5,7];
    let init=0;//累加的初始值,默认为0,可不写
    let b&#duce((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)

参数解析:

  1. pre:必填,表示上一次累加求和的返回值;
            若存在init,则初始值=init;
    若不存在init,则初始值=a[0]
  2. cur:必填,表示当前要累加的数组元素;
  3. index:可选,表示当前要累加的数组元素下标;
    若存在init,则index初始值=0;
    若不存在init,则index初始值=1;
  4. arr:可选,表示当前要处理的原始数组;
  5. 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));//blogconsole.log(array.at(-0));//fafish
console.log(array.at(1));//medium

typeOf:校验数据类型

export const typeOf = function(obj) {return String.call(obj).slice(8, -1).toLowerCase()
}

使用:typeOf(123);//number

手机号脱敏:

export const hideMobile = (mobile) => {place(/^(d{3})d{4}(d{4})$/, "$1****$2")
}

使用:hideMobile('18012345678'); //180****5678

显示全屏:

export const launchFullscreen = (element) => {if (questFullscreen) {questFullscreen()} else if (RequestFullScreen) {RequestFullScreen()} else if (element.msRequestFullscreen) {element.msRequestFullscreen()} else if (element.webkitRequestFullscreen) {element.webkitRequestFullScreen()}
}

关闭全屏:

export const exitFullscreen = () => {if (itFullscreen) {itFullscreen()} else if (document.msExitFullscreen) {document.msExitFullscreen()} else if (CancelFullScreen) {CancelFullScreen()} else if (document.webkitExitFullscreen) {document.webkitExitFullscreen()}
}

大小写转换: 

export const turnCase = (str, type) => {switch (type) {case 1:UpperCase()case 2:LowerCase()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] ies()) {paramsObj[key] = value}return paramsObj
}

使用:getSearchParams();//假如当前地址栏链接为****?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'}]

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) {questAnimationFrame(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 : +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 '' + il(n * k) / k}s = (prec ? toFixedFix(n, prec) : '' + und(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 = ateObjectURL(res.data)let link = ateElement('a')link.style.display = 'none'link.href = urllink.setAttribute('download', fileName + suffix)document.body.appendChild(link)link.click()veChild(link)vokeObjectURL(link.href);}}).catch((err) => {console.ssage);})
}

使用: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 (st(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 ?? ject)(text);

本文发布于:2024-01-31 09:17:48,感谢您对本站的认可!

本文链接:https://www.4u4v.net/it/170666387127471.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:函数   工具   方法   js
留言与评论(共有 0 条评论)
   
验证码:

Copyright ©2019-2022 Comsenz Inc.Powered by ©

网站地图1 网站地图2 网站地图3 网站地图4 网站地图5 网站地图6 网站地图7 网站地图8 网站地图9 网站地图10 网站地图11 网站地图12 网站地图13 网站地图14 网站地图15 网站地图16 网站地图17 网站地图18 网站地图19 网站地图20 网站地图21 网站地图22/a> 网站地图23