前端常用的js工具函数,有效的提高开发效率

7 篇文章 1 订阅

前言:

日常中随着开发经验不断地累积,会用到各种各样的一些工具函数,就从一些网址收藏,自己造的轮子或者别人的轮子,工具函数库进行了整理。

1、校验数据类型

/**
 * 判断变量的类型
 * @param {object} value 变量值
 */
/*方法一*/
export function checkType(value) {
    return Object.prototype.toString.call(value).slice(8, -1)
}
/*方法二*/
export const typeOf = function(value) {
  return Object.prototype.toString.call(value).slice(8, -1).toLowerCase()
}

示例:

typeOf('12345')  // string
typeOf([])  // array
typeOf(new Date())  // date
typeOf(null) // null
typeOf(true) // boolean
typeOf(() => { }) // function

2、防抖

/**
 * 防抖函数
 *
 * @param func 要防抖的函数
 * @param wait 等待时间
 * @param immediate 是否立即执行,为true时立即执行一次,否则在等待时间内只执行一次
 * @returns 返回防抖后的函数
 */
export function debounce(func, wait, immediate) {
    let timeout
    return function() {
        let context = this
        let args = arguments
            //每次执行都清除定时器,判断是否存在只是为了严谨 #不管哪一种都要清除定时器#
        timeout ? clearTimeout(timeout) : null
        if (immediate) {
            var callNow = !timeout
            timeout = setTimeout(() => {
                timeout = null
            }, wait)
            if (callNow) func.apply(context, args)
        } else {
            timeout = setTimeout(function() {
                func.apply(context, args)
            }, wait)
        }
    }
}

示例:

methods: {
  // 确认按钮
    Confirm: debounce(function () {
     console.log('加载数据')
    }, 500),
}

3、节流

export const throttle = (() => {
  let last = 0
  return (callback, wait = 800) => {
    let now = +new Date()
    if (now - last > wait) {
      callback()
      last = now
    }
  }
})()

4、手机号脱敏

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

5、开启全屏

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()
  }
}

6、关闭全屏

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()
  }
}

7、大小写转换

/**
 * 将字符串转换为指定的大小写形式
 *
 * @param str 要转换的字符串
 * @param type 转换类型,1 表示大写,2 表示小写,3 表示首字母大写其余小写
 * @returns 转换后的字符串
 */

export function 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
    }
  }

8、解析URL参数

/**
 * 获取解析URL参数
 *
 * @returns 返回一个对象,包含查询参数
 */
export function getSearchParams() {
  const searchPar = new URLSearchParams(window.location.search)
  const paramsObj = {}
  for (const [key, value] of searchPar.entries()) {
    paramsObj[key] = value
  }
  return paramsObj
}


示例:
// 假设目前位于 https://****com/index?id=154513&age=18;
getSearchParams(); // {id: "154513", age: "18"}
复制代码

9、数组对象根据字段去重

/**
 * 去除数组中重复对象
 *
 * @param arr 待处理的数组
 * @param key 用于比较的键,默认为'id'
 * @returns 返回不重复的对象数组
 */
export function 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
}




示例:

const mockArray = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 3, name: 'Charlie' },
  { id: 1, name: 'Alice' },
  { id: 4, name: 'David' },
  { id: 2, name: 'Bob' },
  { id: 3, name: 'Charlie' },
  { id: 5, name: 'Eve' },
]

uniqueArrayObject(mockArray, 'id')

10、金额格式化

/**
 * 将数字格式化为货币格式
 *
 * @param number 待格式化的数字
 * @param decimals 小数位数,默认为2
 * @param dec_point 小数点,默认为'.'
 * @param thousands_sep 千位分隔符,默认为','
 * @returns 格式化后的字符串
 */

export function 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)
}


示例:
moneyFormat(10000000) // 10,000,000.00
moneyFormat(10000000, 3, '.', '-') // 10-000-000.000
/**
 * 将数字格式化为货币格式
 *
 * @param s 待格式化的数字
 * @param n 小数位数,默认为2位
 * @returns 返回格式化后的货币字符串,千分位显示格式 例:2,100.00 ,点后面不足两位的补全
 */
export function formatPrice(s, n) {
  if (s == null) return s //为null 返回空
  n = n > 0 && n <= 20 ? n : 2;
  s = parseFloat((s + '').replace(/[^\d\.-]/g, '')).toFixed(n) + '';
  var l = s.split('.')[0].split('').reverse();
  var r = s.split('.')[1];
  var t = '';
  for (var i = 0; i < l.length; i++) {
    t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length && l[i + 1] != '-' ? ',' : '');
  }
  return t.split('').reverse().join('') + '.' + r;

}



示例:const formattedPrice = formatPrice(1234.56, 2); // 返回 "1,234.56"

11、下载文件

/**
 * 下载文件
 *
 * @param api 请求的api地址
 * @param params 请求参数
 * @param fileName 文件名
 * @param type 请求方式,默认为'get'
 */
export function 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', {id}, '文件名')

12、遍历树节点

/**
 * 遍历树形数据
 *
 * @param data 树形数据
 * @param callback 回调函数,用于处理每个节点
 * @param childrenName 子节点名称,默认为 'children'
 */
export function foreachTree(data, callback, childrenName = 'children') {
  for (let i = 0; i < data.length; i++) {
    callback(data[i])
    if (data[i][childrenName] && data[i][childrenName].length > 0) {
      foreachTree(data[i][childrenName], callback, childrenName)
    }
  }
}



示例:
假设我们要从树状结构数据中查找 id 为 9 的节点
const treeData = [{
  id: 1,
  label: '一级 1',
  children: [{
    id: 4,
    label: '二级 1-1',
    children: [{
      id: 9,
      label: '三级 1-1-1'
    }, {
      id: 10,
      label: '三级 1-1-2'
    }]
  }]
 }, {
  id: 2,
  label: '一级 2',
  children: [{
    id: 5,
    label: '二级 2-1'
  }, {
    id: 6,
    label: '二级 2-2'
  }]
  }, {
    id: 3,
    label: '一级 3',
    children: [{
      id: 7,
      label: '二级 3-1'
    }, {
      id: 8,
      label: '二级 3-2'
    }]
}],

let result
foreachTree(data, (item) => {
  if (item.id === 9) {
    result = item
  }
})
console.log('result', result)  // {id: 9,label: "三级 1-1-1"}   

13、按钮复制文本内容

/**
 * @description: 复制
 * @param {string} text 文本内容
 */
export const copyText = (text = '') => {
  // http不支持
  if (navigator.clipboard) {
    navigator.clipboard.writeText(text).then(
      () => {
        message.success('复制成功!');
      },
      () => {
        message.warning('复制失败!');
      }
    );
  } else {
    const input = document.createElement('input');
    input.style.position = 'fixed';
    input.style.top = '-10000px';
    input.style.zIndex = '-999';
    document.body.appendChild(input);
    input.value = text;
    input.focus();
    input.select();
    const result = document.execCommand('copy');
    document.body.removeChild(input);
    if (!result) {
      message.warning(
        '当前浏览器不支持复制功能,请检查更新或更换其他浏览器操作!'
      );
    } else {
      message.success('复制成功!');
    }
  }
};

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

柠檬加栤

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值