前端汇总

104 阅读2分钟
//1.## 防抖
export const debounce = (() => {  
  let timer = null  
  return (callback, wait = 800) => {  
    timer&&clearTimeout(timer)  
    timer = setTimeout(callback, wait)  
  }  
})()
示例:
loadList() {  
    debounce(() => {  
      console.log('加载数据')  
    }, 500)  
}
//2.## 节流
export const throttle = (() => {  
  let last = 0  
  return (callback, wait = 800) => {  
    let now = +new Date()  
    if (now - last > wait) {  
      callback()  
      last = now  
    }  
  }  
})()
//3.## 手机号脱敏
export const hideMobile = (mobile) => {  
  return mobile.replace(/^(\d{3})\d{4}(\d{4})$/"$1****$2")  
}
//4.## 开启全屏
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()  
  }  
}
//5.## 关闭全屏
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()  
  }  
}
//6.## 大小写转换  -   type 1-全大写 2-全小写 3-首字母大写
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  
  }  
}
示例:
turnCase('vue'1// VUE  
turnCase('REACT'2// react  
turnCase('vue'3// Vue
//6.## 解析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
}
示例:
// 假设目前位于 https://****com/index?id=154513&age=18;  
getSearchParams(); // {id: "154513", age: "18"}
//7.## 判断手机是Andoird还是IOS
/**   
 * 1: ios  
 * 2: android  
 * 3: 其它  
 */  
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;  
}
//8.## 数组对象根据字段去重
-   arr 要去重的数组
-   key 根据去重的字段名
export const uniqueArrayObject = (arr = [], key = 'id') => {  
  if (arr.length === 0return  
  let list = []  
  const map = {}  
  arr.forEach((item) => {  
    if (!map[item[key]]) {  
      map[item[key]] = item  
    }  
  })  
  list = Object.values(map)  
  
  return list  
}
示例:
const responseList = [  
    { id1name'树哥' },  
    { id2name'黄老爷' },  
    { id3name'张麻子' },  
    { id1name'黄老爷' },  
    { id2name'张麻子' },  
    { id3name'树哥' },  
    { id1name'树哥' },  
    { id2name'黄老爷' },  
    { id3name'张麻子' },  
]  
  
uniqueArrayObject(responseList, 'id')  
// [{ id: 1, name: '树哥' },{ id: 2, name: '黄老爷' },{ id: 3, name: '张麻子' }]
//9.## 滚动到页面顶部
export const scrollToTop = () => {  
  const height = document.documentElement.scrollTop || document.body.scrollTop;  
  if (height > 0) {  
    window.requestAnimationFrame(scrollToTop);  
    window.scrollTo(0, height - height / 8);  
  }  
}
//10.## 滚动到元素位置
export const smoothScroll = element =>{  
    document.querySelector(element).scrollIntoView({  
        behavior'smooth'  
    });  
};
示例:
smoothScroll('#target'); // 平滑滚动到 ID 为 target 的元素
//11.## uuid
export const uuid = () => {  
  const temp_url = URL.createObjectURL(new Blob())  
  const uuid = temp_url.toString()  
  URL.revokeObjectURL(temp_url) //释放这个url  
  return uuid.substring(uuid.lastIndexOf('/') + 1)  
}
uuid() // a640be34-689f-4b98-be77-e3972f9bffdd
//12.## 金额格式化
-   {number} number:要格式化的数字
-   {number} decimals:保留几位小数
-   {string} dec_point:小数点符号
-   {string} thousands_sep:千分位符号
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)  
}
示例:
moneyFormat(10000000// 10,000,000.00  
moneyFormat(100000003'.''-'// 10-000-000.000
//13.## 存储操作
class MyCache {  
  constructor(isLocal = true) {  
    this.storage = isLocal ? localStorage : sessionStorage  
  }  
  
  setItem(key, value) {  
    if (typeof (value) === 'object') value = JSON.stringify(value)  
    this.storage.setItem(key, value)  
  }  
  
  getItem(key) {  
    try {  
      return JSON.parse(this.storage.getItem(key))  
    } catch (err) {  
      return this.storage.getItem(key)  
    }  
  }  
  
  removeItem(key) {  
    this.storage.removeItem(key)  
  }  
  
  clear() {  
    this.storage.clear()  
  }  
  
  key(index) {  
    return this.storage.key(index)  
  }  
  
  length() {  
    return this.storage.length  
  }  
}  
  
const localCache = new MyCache()  
const sessionCache = new MyCache(false)  
  
export { localCache, sessionCache }
示例:
localCache.getItem('user')  
sessionCache.setItem('name','树哥')  
sessionCache.getItem('token')  
localCache.clear()
//14.## 下载文件
-   api 接口
-   params 请求参数
-   fileName 文件名
const downloadFile = (api, params, fileName, type = 'get') => {  
  axios({  
    methodtype,  
    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}, '文件名')
//15.## 时间操作
Day.js 是一个仅 2kb 大小的轻量级 JavaScript 时间日期处理库,下载、解析和执行的JavaScript更少,为代码留下更多的时间。
//16.## 深拷贝
**完备的深拷贝,推荐使用 lodash 中的 cloneDeep 方法。**
//17.## 模糊搜索
-   list 原数组
-   keyWord 查询的关键词
-   attribute 数组需要检索属性
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  
}
示例:
const list = [  
  { id1name'树哥' },  
  { id2name'黄老爷' },  
  { id3name'张麻子' },  
  { id4name'汤师爷' },  
  { id5name'胡万' },  
  { id6name'花姐' },  
  { id7name'小梅' }  
]  
fuzzyQuery(list, '树''name'// [{id: 1, name: '树哥'}]
//18.## 遍历树节点
export const 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)  
    }  
  }  
}
示例:
const treeData = [{  
  id1,  
  label'一级 1',  
  children: [{  
    id4,  
    label'二级 1-1',  
    children: [{  
      id9,  
      label'三级 1-1-1'  
    }, {  
      id10,  
      label'三级 1-1-2'  
    }]  
  }]  
 }, {  
  id2,  
  label'一级 2',  
  children: [{  
    id5,  
    label'二级 2-1'  
  }, {  
    id6,  
    label'二级 2-2'  
  }]  
  }, {  
    id3,  
    label'一级 3',  
    children: [{  
      id7,  
      label'二级 3-1'  
    }, {  
      id8,  
      label'二级 3-2'  
    }]  
}],  
  
let result  
foreachTree(data, (item) => {  
  if (item.id === 9) {  
    result = item  
  }  
})  
console.log('result', result)  // {id: 9,label: "三级 1-1-1"}
//45.# 前端经典面试题 ( 60道前端面试题包含 JS、CSS、React、网络、浏览器、程序题等)
https://mp.weixin.qq.com/s/oP_GAkAliSidJScKRySyqg
//46.# JavaScript 中的内存泄漏
https://mp.weixin.qq.com/s/TEs6JKQsRo2ZbVhVfAuOBA
//47.# 一文吃透 Webpack 核心原理
https://mp.weixin.qq.com/s/Jw_-cZepryo9nbnk1mwjjw
//48.# 当面试官问Webpack的时候他想知道什么
https://mp.weixin.qq.com/s/xhIybguJlQ6pJgmaGsDbAw
//49.# 字节跳动最爱考的前端面试题:JavaScript 基础
https://mp.weixin.qq.com/s/PUAOEIl7jL-lOmzj6aVXsA
//50.# 你真的懂 Promise 吗?
https://mp.weixin.qq.com/s/zcZwMRg9nymQrp4n6FEldA
//51.# 面试官:说说你对 React diff的理解?原理是什么?
https://mp.weixin.qq.com/s/Xxm7ok-m9hdufn6ui10lMQ
//52.# JavaScript 实现 bind 的这五层,你在第几层?
https://mp.weixin.qq.com/s/nI8VHuVQP73DGBrBdh5i2w
//53.# 浅谈前端权限设计方案
https://mp.weixin.qq.com/s/aOt_JtYycGRPy0DShQySjA
//54.# 在项目中用 TS 封装 axios ,一次封装团队受益
https://mp.weixin.qq.com/s/o032SSrQbhPR9QXE_wdJ-g
//55.# 微信 H5 页面兼容性解决方案
https://mp.weixin.qq.com/s/6dhFnUviXGj5gT-FfB8gXw
//56.# 让你 vscode 写代码效率更高的技巧
https://mp.weixin.qq.com/s/9AgAe5u0Go7JN6XJ3jhHZQ
//57.# 异步中 0 秒的定时器为什么要加?它会立即执行吗?
https://mp.weixin.qq.com/s/V-cBw4MXuSUSOauyiXYPHQ
//58.# 一文吃透 react-hooks 原理
https://mp.weixin.qq.com/s/3ejFeGKXGV4HXgO4mwcPMA
//59.# React 全部 api 解读+基础实践大全
https://mp.weixin.qq.com/s/wdChmE2-UDNFVyzG7RV0sg