跳至主要內容

JS工具函数

知识库编程技巧JavaScriptJavaScript大约 12 分钟

slice,splice,split的区别

  • slice
    用法:array.slice(start,end),含头不含尾
    解释:该方法是对数组或者字符串进行部分截取,并返回一个数副本;

    console.log([1,2,3,4,5,6].slice(0,3));    //[1,2,3]
    console.log([1,2,3,4,5,6].slice(3));      //[4,5,6]
    console.log([1,2,3,4,5,6].slice(8));      //[]
    console.log([1,2,3,4,5,6].slice(-1));     //[6]
    console.log([1,2,3,4,5,6].slice(-8));     //[1, 2, 3, 4, 5, 6]
    console.log([1,2,3,4,5,6].slice(2,-3));   //[3]
    console.log("123456".slice(0,3));       //"123"
    console.log("123456".slice(3));         //"456"
    console.log("123456".slice(8));         //""
    console.log("123456".slice(-1));        //"6"
    console.log("123456".slice(-8));        //"123456"
    console.log("123456".slice(2,-3));      //"3"
    
  • splice
    用法:array.splice(start,deleteCount,item...)
    解释:splice方法从array中移除一个或多个数组,并用新的item替换它们。
    参数:

    • start是从数组array中移除元素的开始位置。
    • deleteCount是要移除的元素的个数。
    • 如果有额外的参数,那么item会插入到被移除元素的位置上。
      返回:一个包含被移除元素的数组。
    var a=['a','b','c'];
    console.log(a.splice(1,1,'e','f'));  //["b"]
    console.log(a);       //["a", "e", "f", "c"]
    
  • split
    用法:string.split(separator,limit)
    解释:split方法把这个string分割成片段来创建一个字符串数组。
    参数:

    • separator参数可以是一个字符串或一个正则表达式
    • limit可以限制被分割的片段数量
    console.log("0123456".split("",3));  //b=["0","1","2"]
    

生成一周时间

new Array 创建的数组只是添加了length属性,并没有实际的内容。通过扩展后,变为可用数组用于循环。

function getWeekTime(){
  return [...new Array(7)].map((j,i)=> new Date(Date.now()+i*8.64e7).toLocaleDateString())
}
getWeekTime();// ["2020/2/26", "2020/2/27", "2020/2/28", "2020/2/29", "2020/3/1", "2020/3/2", "2020/3/3"]

获取元素类型

const dataType = obj => Object.prototype.toString.call(obj).replace(/^\[object (.+)\]$/, '$1').toLowerCase();
dataType("");   //"string"

类 型 判 断

判断核心使用Object.prototype.toString,这种方式可以准确的判断数据类型。

 /**
 * @param {any} target
 * @param {string} type
 * @return {boolean}
 */
function isType(target, type) {
    let targetType = Object.prototype.toString.call(target).slice(8, -1).toLowerCase()
    return targetType === type.toLowerCase()
}
isType([], 'Array');                // true
isType(/\d/, 'RegExp');             // true
isType(new Date(), 'Date');         // true
isType(function(){}, 'Function');   // true
isType(Symbol(1), 'Symbol');        // true

简单的交换变量

你可能使用第三个变量 temp 交换两个变量。但是这个技巧将向你展示一种使用解构来交换变量的新方法。

var a = 6;
var b = 7;
[a,b] = [b,a]
console.log(a,b) // 7 6

对象属性剔除

应用场景很简单,当你需要使用一个对象,但想移除部分属性时,可以使用该方法。同样的,你可以实现一个对象属性选取方法。

/**
 * @param {object} object
 * @param {string[]} props
 * @return {object}
 */
function omit(object, props=[]){
    let res = {};
    Object.keys(object).forEach(key=>{
        if (props.includes(key) === false) {
            res[key] = typeof object[key] === 'object' && object[key] !== null ?
            jsON.parse(jsON.stringify(object[key])):
            object[key]
        }
    });
    return res
}
omit({id: 1,title: 'title',comment: []}, ['id']);       // {title: 'title', comment: []}

日期格式化

一个很灵活的日期格式化函数,可以根据使用者给定的格式进行格式化,能应对大部分场景。

/**
 * @param {string} format
 * @param {number} timestamp - 时间戳
 * @return {string}
 */
function formatDate(format='Y-M-D h:m', timestamp=Date.now()){
    let date = new Date(timestamp)
    let dateInfo = {
    Y: date.getFullYear(),
    M: date.getMonth()+1,
    D: date.getDate(),
    h: date.getHours(),
    m: date.getMinutes(),
    s: date.getSeconds()
    }
    let formatNumber = (n) => n > 10 ? n : '0' + n
    let res = format
    .replace('Y', dateInfo.Y)
    .replace('M', dateInfo.M)
    .replace('D', dateInfo.D)
    .replace('h', formatNumber(dateInfo.h))
    .replace('m', formatNumber(dateInfo.m))
    .replace('s', formatNumber(dateInfo.s))
    return res
}
formatDate();                   // "2020-2-24 13:44"
formatDate('M月D日 h:m');        // "2月24日 13:45"
formatDate('h:m Y-M-D', 1582526221604);     //"14:37 2020-2-24"

性 能 分 析

Web Performance API允许网页访问某些函数来测量网页和Web应用程序的性能。
performance.timing 包含延迟相关的性能信息。
performance.memory 包含内存信息,是Chrome中添加的一个非标准扩展,在使用时需要注意。

window.onload = function(){
  setTimeout(()=>{
    let t = performance.timing,
        m = performance.memory
    console.table({
      'DNS查询耗时': (t.domainLookupEnd - t.domainLookupStart).toFixed(0),
      'TCP链接耗时': (t.connectEnd - t.connectStart).toFixed(0),
      'request请求耗时': (t.responseEnd - t.responseStart).toFixed(0),
      '解析dom树耗时': (t.domComplete - t.domInteractive).toFixed(0),
      '白屏时间': (t.responseStart - t.navigationStart).toFixed(0),
      'domready时间': (t.domContentLoadedEventEnd - t.navigationStart).toFixed(0),
      'onload时间': (t.loadEventEnd - t.navigationStart).toFixed(0),
      'js内存使用占比': m ? (m.usedjsHeapSize / m.totaljsHeapSize * 100).toFixed(2) + '%' : undefined
    })
  })
}

延迟函数delay

const delay = ms => new Promise((resolve, reject) => setTimeout(resolve, ms));
const getData = status => new Promise((resolve, reject) => {
     status ? resolve('done') : reject('fail')
});
const getRes = async (data) => {
     try {
         const res = await getData(data)
         const timestamp = new Date().getTime()
         await delay(1000);
         console.log(res, new Date().getTime() - timestamp)
     } catch (error) {
         console.log(error)
     }
 };
getRes(true); // 隔了1秒

防 抖

性能优化方案,防抖用于减少函数请求次数,对于频繁的请求,只执行这些请求的最后一次。

基础版本

function debounce(func, wait = 300){
  let timer = null;
  return function(){
    if(timer !== null){
      clearTimeout(timer);
    }
    timer = setTimeout(fn,wait);
  }
}

改进版本添加是否立即执行的参数,因为有些场景下,我们希望函数能立即执行。

/**
 * @param {function} func - 执行函数
 * @param {number} wait - 等待时间
 * @param {boolean} immediate - 是否立即执行
 * @return {function}
 */
function debounce(func, wait = 300, immediate = false){
    let timer, ctx;
    let later = (arg) => setTimeout(()=>{
    func.apply(ctx, arg)
    timer = ctx = null
    }, wait)
    return function(...arg){
    if(!timer){
      timer = later(arg)
      ctx = this
      if(immediate){
        func.apply(ctx, arg)
      }
    }else{
      clearTimeout(timer)
      timer = later(arg)
    }
    }
}
let scrollHandler = debounce(function(e){
  console.log(e)
}, 500);

节 流

性能优化方案,节流用于减少函数请求次数,与防抖不同,节流是在一段时间执行一次。

/**
 * @param {function} func - 执行函数
 * @param {number} delay - 延迟时间
 * @return {function}
 */
function throttle(func, delay){
    let timer = null
    return function(...arg){
    if(!timer){
      timer = setTimeout(()=>{
        func.apply(this, arg)
        timer = null
      }, delay)
    }
    }
}
let scrollHandler = throttle(function(e){
  console.log(e)
}, 500);

base64数据导出文件下载

/**
 * @param {string} filename - 下载时的文件名
 * @param {string} data - base64字符串
 */
function downloadFile(filename, data){
    let downloadLink = document.createElement('a');
    if ( downloadLink ){
    document.body.appendChild(downloadLink);
    downloadLink.style = 'display: none';
    downloadLink.download = filename;
    downloadLink.href = data;
    if ( document.createEvent ){
      let downloadEvt = document.createEvent('MouseEvents');
      downloadEvt.initEvent('click', true, false);
      downloadLink.dispatchEvent(downloadEvt);
    } else if ( document.createEventObject ) {
      downloadLink.fireEvent('onclick');
    } else if (typeof downloadLink.onclick == 'function' ) {
      downloadLink.onclick();
    }
    document.body.removeChild(downloadLink);
    }
}

检测是否为PC端浏览器

function isPCBroswer() {
  let e = window.navigator.userAgent.toLowerCase()
    , t = "ipad" == e.match(/ipad/i)
    , i = "iphone" == e.match(/iphone/i)
    , r = "midp" == e.match(/midp/i)
    , n = "rv:1.2.3.4" == e.match(/rv:1.2.3.4/i)
    , a = "ucweb" == e.match(/ucweb/i)
    , o = "android" == e.match(/android/i)
    , s = "windows ce" == e.match(/windows ce/i)
    , l = "windows mobile" == e.match(/windows mobile/i);
  return !(t || i || r || n || a || o || s || l)
}

识别浏览器及平台

function getPlatformInfo(){
  //运行环境是浏览器
  let inBrowser = typeof window !== 'undefined';
  //运行环境是微信
  let inWeex = typeof WXEnvironment !== 'undefined' && !!WXEnvironment.platform;
  let weexPlatform = inWeex && WXEnvironment.platform.toLowerCase();
  //浏览器 UA 判断
  let UA = inBrowser && window.navigator.userAgent.toLowerCase();
  if(UA){
    let platforms = {
      IE: /msie|trident/.test(UA),
      IE9: UA.indexOf('msie 9.0') > 0,
      Edge: UA.indexOf('edge/') > 0,
      Android: UA.indexOf('android') > 0 || (weexPlatform === 'android'),
      IOS: /iphone|ipad|ipod|ios/.test(UA) || (weexPlatform === 'ios'),
      Chrome: /chrome\/\d+/.test(UA) && !(UA.indexOf('edge/') > 0),
    }
    for (const key in platforms) {
      if (platforms.hasOwnProperty(key)) {
        if(platforms[key]) return key
      }
    }
  }
}

函数柯里化

const curring = fn => {
     const { length } = fn
     const curried = (...args) => {
         return (args.length >= length
               ? fn(...args)
               : (...args2) => curried(...args.concat(args2)))
     }
     return curried
 };
 const listMerge = (a, b, c) => [a, b, c]
 const curried = curring(listMerge);

 console.log(curried(1)(2)(3));     // [1, 2, 3]
 console.log(curried(1, 2)(3));     // [1, 2, 3]
 console.log(curried(1, 2, 3));     // [1, 2, 3]

字符串前面空格去除与替换

const trimStart = str => str.replace(new RegExp('^([\\s]*)(.*)$'), '$2');

console.log(trimStart(' abc '));        // abc
console.log(trimStart('123 '));          // 123

字符串后面空格去除与替换

const trimEnd = str => str.replace(new RegExp('^(.*?)([\\s]*)$'), '$1')

console.log(trimEnd(' abc '));      //   abc
console.log(trimEnd('123 '));       // 123

获取当前子元素是其父元素下子元素的排位

const getIndex = el => {
     if (!el) {
         return -1
     }
     let index = 0;
     do {
         index++
     } while (el = el.previousElementSibling);
     return index
 }

获取当前元素相对于document的偏移量

const getOffset = el => {
    const {top,left} = el.getBoundingClientRect();
    const {scrollTop,scrollLeft} = document.body;
    return {top: top + scrollTop,left: left + scrollLeft}
}

判断是否是移动端

const isMobile = () => 'ontouchstart' in window;

fade动画

const fade = function(el, type = 'in') {
     el.style.opacity = (type === 'in' ? 0 : 1)
     let last = +new Date();
     const tick = () => {
         const opacityValue = (type === 'in' 
                             ? (new Date() - last) / 400
                             : -(new Date() - last) / 400)
         el.style.opacity = +el.style.opacity + opacityValue
         last = +new Date();
         if (type === 'in'
           ? (+el.style.opacity < 1)
           : (+el.style.opacity > 0)) {
             requestAnimationFrame(tick)
         }
     };
     tick();
 };

将指定格式的字符串解析为日期字符串

const dataPattern = (str, format = '-') => {
     if (!str) {
         return new Date()
     }
     const dateReg = new RegExp(`^(\\d{2})${format}(\\d{2})${format}(\\d{4})$`)
     const [, month, day, year] = dateReg.exec(str);
     return new Date(`${month}, ${day} ${year}`)
 };

console.log(dataPattern('12-25-1995'));         // Mon Dec 25 1995 00:00:00 GMT+0800 (中国标准时间)

禁止网页复制粘贴

const html = document.querySelector('html')
 html.oncopy = () => false;
 html.onpaste = () => false;

input框限制只能输入中文

const input = document.querySelector('input[type="text"]')
const clearText = target => {
     const {value} = target;
     target.value = value.replace(/[^\u4e00-\u9fa5]/g, '')
 };
 input.onfocus = ({target}) => {
     clearText(target)
 };
 input.onkeyup = ({target}) => {
     clearText(target)
 };
 input.onblur = ({target}) => {
     clearText(target)
 };
 input.oninput = ({target}) => {
     clearText(target)
 }

去除字符串中的html代码

const removehtml = (str = '') => str.replace(/<[\/\!]*[^<>]*>/ig, '');
console.log(removehtml('<h1>哈哈哈哈<呵呵呵</h1>'));       // 哈哈哈哈<呵呵呵

1、校验数据类型

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

示例:

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

2、防抖

export const debounce = (() => {
  let timer = null
  return (callback, wait = 800) => {
    timer&&clearTimeout(timer)
    timer = setTimeout(callback, wait)
  }
})()

示例:

如 vue 中使用

methods: {
  loadList() {
    debounce(() => {
      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) =>  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、大小写转换

参数:

  • str 待转换的字符串
  • 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

8、解析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"}

9、判断手机是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;
}

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

参数:

  • arr 要去重的数组
  • key 根据去重的字段名
export const 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 responseList = [
    { id: 1, name: '树哥' },
    { id: 2, name: '黄老爷' },
    { id: 3, name: '张麻子' },
    { id: 1, name: '黄老爷' },
    { id: 2, name: '张麻子' },
    { id: 3, name: '树哥' },
    { id: 1, name: '树哥' },
    { id: 2, name: '黄老爷' },
    { id: 3, name: '张麻子' },
]

uniqueArrayObject(responseList, 'id')
// [{ id: 1, name: '树哥' },{ id: 2, name: '黄老爷' },{ id: 3, name: '张麻子' }]

11、滚动到页面顶部

export const scrollToTop = () => {
  const height = document.documentElement.scrollTop || document.body.scrollTop;
  if (height > 0) {
    window.requestAnimationFrame(scrollToTop);
    window.scrollTo(0, height - height / 8);
  }
}

12、滚动到元素位置

export const smoothScroll = element => document.querySelector(element).scrollIntoView({ behavior: 'smooth' });

示例:

smoothScroll('#target'); // 平滑滚动到 ID 为 target 的元素

13、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

不过要吐槽一句的是,uuid一般应由后端来进行生成

14、金额格式化

参数:

  • {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(10000000, 3, '.', '-') // 10-000-000.000

15、存储操作

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

16、下载文件

参数:

  • api 接口
  • params 请求参数
  • fileName 文件名
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 = 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}, '文件名')

17、时间操作

关于时间操作,没必要自己再写一大串代码了,强烈推荐使用 day.js

Day.js 是一个仅 2kb 大小的轻量级 JavaScript 时间日期处理库,下载、解析和执行的JavaScript更少,为代码留下更多的时间。

18、深拷贝

export const clone = parent => {
  // 判断类型
  const isType = (obj, type) => {
    if (typeof obj !== "object") return false;
    const typeString = Object.prototype.toString.call(obj);
    let flag;
    switch (type) {
      case "Array":
        flag = typeString === "[object Array]";
        break;
      case "Date":
        flag = typeString === "[object Date]";
        break;
      case "RegExp":
        flag = typeString === "[object RegExp]";
        break;
      default:
        flag = false;
    }
    return flag;
  };

  // 处理正则
  const getRegExp = re => {
    var flags = "";
    if (re.global) flags += "g";
    if (re.ignoreCase) flags += "i";
    if (re.multiline) flags += "m";
    return flags;
  };
  // 维护两个储存循环引用的数组
  const parents = [];
  const children = [];

  const _clone = parent => {
    if (parent === null) return null;
    if (typeof parent !== "object") return parent;

    let child, proto;

    if (isType(parent, "Array")) {
      // 对数组做特殊处理
      child = [];
    } else if (isType(parent, "RegExp")) {
      // 对正则对象做特殊处理
      child = new RegExp(parent.source, getRegExp(parent));
      if (parent.lastIndex) child.lastIndex = parent.lastIndex;
    } else if (isType(parent, "Date")) {
      // 对Date对象做特殊处理
      child = new Date(parent.getTime());
    } else {
      // 处理对象原型
      proto = Object.getPrototypeOf(parent);
      // 利用Object.create切断原型链
      child = Object.create(proto);
    }

    // 处理循环引用
    const index = parents.indexOf(parent);

    if (index != -1) {
      // 如果父数组存在本对象,说明之前已经被引用过,直接返回此对象
      return children[index];
    }
    parents.push(parent);
    children.push(child);

    for (let i in parent) {
      // 递归
      child[i] = _clone(parent[i]);
    }

    return child;
  };
  return _clone(parent);
};

此方法存在一定局限性:一些特殊情况没有处理: 例如Buffer对象、Promise、Set、Map。

如果确实想要完备的深拷贝,推荐使用 lodash 中的 cloneDeep 方法。

19、模糊搜索

参数:

  • 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 = [
  { 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: '树哥'}]

20、遍历树节点

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

示例:

假设我们要从树状结构数据中查找 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"}