• JS使用工具函数


    1、校验数据类型

    1. export const typeOf = function(obj) {
    2. return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase()
    3. }
    4. //示例代码
    5. typeOf([]) // array
    6. typeOf(null) //null
    7. typeOf(() => {}) //function

    2、数组对象根据某一个字段去重

    1. // arr-> 表示要去重数组, key-> 表示要去重的字段
    2. export const uniqueArrayObject = (arr = [], key = 'id') => {
    3. if (arr.length === 0) return
    4. let list = []
    5. const map = {}
    6. arr.forEach((item) => {
    7. if (!map[item[key]]) {
    8. map[item[key]] = item
    9. }
    10. })
    11. list = Object.values(map)
    12. return list
    13. }
    14. //示例
    15. const list = [
    16. { id: 1, name: '张三' },
    17. { id: 2, name: '黄老爷' },
    18. { id: 3, name: '张麻子' },
    19. { id: 1, name: '黄老爷' },
    20. { id: 2, name: '张三' },
    21. { id: 3, name: '树哥' },
    22. { id: 1, name: '树哥' },
    23. { id: 2, name: '黄老爷' },
    24. { id: 3, name: '张麻子' },
    25. ]
    26. uniqueArrayObject(list, 'id')

    3、滚动到元素位置

    1. export const smoothScroll = element =>{
    2. document.querySelector(element).scrollIntoView({
    3. behavior: 'smooth'
    4. });
    5. };
    6. //示例
    7. smoothScroll('#target'); // 平滑滚动到 ID 为 target 的元素

    4、滚动到页面顶部

    1. export const scrollToTop = () => {
    2. const height = document.documentElement.scrollTop || document.body.scrollTop;
    3. if (height > 0) {
    4. window.requestAnimationFrame(scrollToTop);
    5. window.scrollTo(0, height - height / 8);
    6. }
    7. }
    8. //示例
    9. scrollToTop()

    5、金额格式化

    1. export const moneyFormat = (number, decimals, dec_point, thousands_sep) => {
    2. number = (number + '').replace(/[^0-9+-Ee.]/g, '')
    3. const n = !isFinite(+number) ? 0 : +number
    4. const prec = !isFinite(+decimals) ? 2 : Math.abs(decimals)
    5. const sep = typeof thousands_sep === 'undefined' ? ',' : thousands_sep
    6. const dec = typeof dec_point === 'undefined' ? '.' : dec_point
    7. let s = ''
    8. const toFixedFix = function(n, prec) {
    9. const k = Math.pow(10, prec)
    10. return '' + Math.ceil(n * k) / k
    11. }
    12. s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.')
    13. const re = /(-?\d+)(\d{3})/
    14. while (re.test(s[0])) {
    15. s[0] = s[0].replace(re, '$1' + sep + '$2')
    16. }
    17. if ((s[1] || '').length < prec) {
    18. s[1] = s[1] || ''
    19. s[1] += new Array(prec - s[1].length + 1).join('0')
    20. }
    21. return s.join(dec)
    22. }
    23. //示例
    24. moneyFormat(10000000) // 10,000,000.00
    25. moneyFormat(10000000, 3, '.', '-') // 10-000-000.000

    6、下载文件

    1. // api -> 接口, params -> 请求参数, fileName -> 文件名
    2. const downloadFile = (api, params, fileName, type = 'get') => {
    3. axios({
    4. method: type,
    5. url: api,
    6. responseType: 'blob',
    7. params: params
    8. }).then((res) => {
    9. let str = res.headers['content-disposition']
    10. if (!res || !str) {
    11. return
    12. }
    13. let suffix = ''
    14. // 截取文件名和文件类型
    15. if (str.lastIndexOf('.')) {
    16. fileName ? '' : fileName = decodeURI(str.substring(str.indexOf('=') + 1, str.lastIndexOf('.')))
    17. suffix = str.substring(str.lastIndexOf('.'), str.length)
    18. }
    19. // 如果支持微软的文件下载方式(ie10+浏览器)
    20. if (window.navigator.msSaveBlob) {
    21. try {
    22. const blobObject = new Blob([res.data]);
    23. window.navigator.msSaveBlob(blobObject, fileName + suffix);
    24. } catch (e) {
    25. console.log(e);
    26. }
    27. } else {
    28. // 其他浏览器
    29. let url = window.URL.createObjectURL(res.data)
    30. let link = document.createElement('a')
    31. link.style.display = 'none'
    32. link.href = url
    33. link.setAttribute('download', fileName + suffix)
    34. document.body.appendChild(link)
    35. link.click()
    36. document.body.removeChild(link)
    37. window.URL.revokeObjectURL(link.href);
    38. }
    39. }).catch((err) => {
    40. console.log(err.message);
    41. })
    42. }`
    43. //示例
    44. downloadFile('/api/download', {id}, '文件名')

    7、遍历树节点

    1. export const foreachTree = (data, callback, childrenName = 'children') => {
    2. for (let i = 0; i < data.length; i++) {
    3. callback(data[i])
    4. if (data[i][childrenName] && data[i][childrenName].length > 0) {
    5. foreachTree(data[i][childrenName], callback, childrenName)
    6. }
    7. }
    8. }
    9. //示例
    10. const treeData = [{
    11. id: 1,
    12. label: '一级 1',
    13. children: [{
    14. id: 4,
    15. label: '二级 1-1',
    16. children: [{
    17. id: 9,
    18. label: '三级 1-1-1'
    19. }, {
    20. id: 10,
    21. label: '三级 1-1-2'
    22. }]
    23. }]
    24. }, {
    25. id: 2,
    26. label: '一级 2',
    27. children: [{
    28. id: 5,
    29. label: '二级 2-1'
    30. }, {
    31. id: 6,
    32. label: '二级 2-2'
    33. }]
    34. }, {
    35. id: 3,
    36. label: '一级 3',
    37. children: [{
    38. id: 7,
    39. label: '二级 3-1'
    40. }, {
    41. id: 8,
    42. label: '二级 3-2'
    43. }]
    44. }],
    45. let result
    46. foreachTree(data, (item) => {
    47. if (item.id === 9) {
    48. result = item
    49. }
    50. })
    51. console.log('result', result) // {id: 9,label: "三级 1-1-1"}

    8、对象格式的参数转成键值对,并以&分

    1. /**
    2. * 把对象格式的参数转成键值对,并以&分割
    3. * @param arr 要转换的对象参数
    4. * @returns {string}
    5. */
    6. function maiyaBuildParam(arr){
    7. var result = '';
    8. for(var key in arr)
    9. {
    10. result += key + "=" + encodeURIComponent(arr[key]) + "&";
    11. }
    12. result = result.substr(0,result.length-1);
    13. return result;
    14. }
    '
    运行

    9、刷新当前页面

    1. //刷新当前页面
    2. location.reload();

    10、强制页面横屏展示

    1. $( window ).on( "orientationchange", function( event ) {
    2. if (event.orientation=='portrait') {
    3. $('body').css('transform', 'rotate(90deg)');
    4. } else {
    5. $('body').css('transform', 'rotate(0deg)');
    6. }
    7. });
    8. $( window ).orientationchange();

    11、时间倒计时

    1. function countdown() {
    2. var endtime = new Date("May 2, 2023 00:00:00");
    3. var nowtime = new Date();
    4. if (nowtime >= endtime) {
    5. document.getElementById("clock").innerHTML = "倒计时间结束";
    6. return;
    7. }
    8. var leftsecond = parseInt((endtime.getTime() - nowtime.getTime()) / 1000);
    9. if (leftsecond < 0) {
    10. leftsecond = 0;
    11. }
    12. d = parseInt(leftsecond / 3600 / 24);
    13. h = parseInt((leftsecond / 3600) % 24);
    14. m = parseInt((leftsecond / 60) % 60);
    15. s = parseInt(leftsecond % 60);
    16. document.getElementById("clock").innerHTML = d + "天" + h + "小时" + m + "分" + s + "秒";
    17. }
    18. countdown();
    19. setInterval(countdown, 1000);

    12、翻转字符串

    const reverse = str => str.split('').reverse().join('');'
    运行

    13、检测用户处于暗模式

    const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches

    14、实现base64解码

    1. function base64_decode(data) {
    2. var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    3. var o1,
    4. o2,
    5. o3,
    6. h1,
    7. h2,
    8. h3,
    9. h4,
    10. bits,
    11. i = 0,
    12. ac = 0,
    13. dec = "",
    14. tmp_arr = [];
    15. if (!data) {
    16. return data;
    17. }
    18. data += "";
    19. do {
    20. h1 = b64.indexOf(data.charAt(i++));
    21. h2 = b64.indexOf(data.charAt(i++));
    22. h3 = b64.indexOf(data.charAt(i++));
    23. h4 = b64.indexOf(data.charAt(i++));
    24. bits = (h1 << 18) | (h2 << 12) | (h3 << 6) | h4;
    25. o1 = (bits >> 16) & 0xff;
    26. o2 = (bits >> 8) & 0xff;
    27. o3 = bits & 0xff;
    28. if (h3 == 64) {
    29. tmp_arr[ac++] = String.fromCharCode(o1);
    30. } else if (h4 == 64) {
    31. tmp_arr[ac++] = String.fromCharCode(o1, o2);
    32. } else {
    33. tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
    34. }
    35. } while (i < data.length);
    36. dec = tmp_arr.join("");
    37. dec = utf8_decode(dec);
    38. return dec;
    39. }
    '
    运行

    15、获取URL上的参数

    1. // 获取URL中的某参数值,不区分大小写
    2. // 默认是取'hash'里的参数,
    3. // 如果传其他参数支持取‘search’中的参数
    4. // @param {String} name 参数名称
    5. export function getUrlParam(name, type = "hash") {
    6. let newName = name,
    7. reg = new RegExp("(^|&)" + newName + "=([^&]*)(&|$)", "i"),
    8. paramHash = window.location.hash.split("?")[1] || "",
    9. paramSearch = window.location.search.split("?")[1] || "",
    10. param;
    11. type === "hash" ? (param = paramHash) : (param = paramSearch);
    12. let result = param.match(reg);
    13. if (result != null) {
    14. return result[2].split("/")[0];
    15. }
    16. return null;
    17. }

    16、修改url中的参数 

    1. /**
    2. * @param { string } paramName
    3. * @param { string } replaceWith
    4. */
    5. export function replaceParamVal(paramName,replaceWith) {
    6. var oUrl = location.href.toString();
    7. var re=eval('/('+ paramName+'=)([^&]*)/gi');
    8. location.href = oUrl.replace(re,paramName+'='+replaceWith);
    9. return location.href;
    10. }

    17、安卓移动设备访问

    1. function isAndroidMobileDevice() {
    2. return /android/i.test(navigator.userAgent.toLowerCase());
    3. }
    '
    运行

    18、苹果移动设备访问

    1. function isAppleMobileDevice() {
    2. return /iphone|ipod|ipad|Macintosh/i.test(navigator.userAgent.toLowerCase());
    3. }
    '
    运行

    19、平滑滚动到页面顶部

    1. export const scrollToTop = () => {
    2. const c = document.documentElement.scrollTop || document.body.scrollTop;
    3. if (c > 0) {
    4. window.requestAnimationFrame(scrollToTop);
    5. window.scrollTo(0, c - c / 8);
    6. }
    7. };

    发现更好的工具函数 ,持续更新中...

    参考文献

    https://github.com/any86/any-...
    https://juejin.im/post/5cc7af...
    https://juejin.im/post/5da1a0...
    https://juejin.im/post/5deb2c...
    https://juejin.im/post/5de5be...

  • 相关阅读:
    银行基于云原生架构下的 DevOps 建设实践经验
    windows局域网传文件5种常用方法
    通过Power Platform自定义D365 CE 业务需求 - 5. 使用Power Virtual Agent
    Leetcode 2269. 找到一个数字的 K 美丽值(滑动窗口)
    计算机网络-网络层篇-IP协议
    Python networkX共现图,通过LDA主题关键词共现
    i2c协议的特点是什么,老司机带你深入了解
    GIL全局解释器锁
    人工神经元网络基本构成,人工神经网络主要有
    成都收录《乡村振兴战略下传统村落文化旅游设计》许少辉八一著作
  • 原文地址:https://blog.csdn.net/codingLeader/article/details/126902766