笔试中,经常会遇到的几类函数封装

172 阅读1分钟

冒泡排序

let Arr = [12, 34, 6, 32, 14, 77, 34, 12, 6, 4, 3]

function sort (arr) {
  for (let i = 0; i < arr.length - 1; i++) {
    for (let j = 0; j < arr.length - 1; j++) {
      let num = arr[j + 1] - arr[j]
      let temp
      if (num < 0) {
        temp = arr[j]
        arr[j] = arr[j + 1]
        arr[j + 1] = temp
      }
    }
  }
}

sort(Arr)
console.log(Arr)

数组去重

let Arr = [2, 2, 4, 6, 78, 6, 34, 23, 13, 56]
function set (arr) {
  let shuzu = []
  Arr = arr.filter((item, index) => {
    let bol = true
    arr.forEach((item1, index1) => {
      let a = item == item1
      let b = index !== index1
      if (a && b) {
        bol = false
        let c = shuzu.every((item3, index3) => {
          return item != item3
        })
        if (c) {
          shuzu.push(item)
        }
      }
    })
    if (!bol) {
    }
    return bol
  })
  arr = [...Arr, ...shuzu]
}

set(Arr)
console.log(Arr)

防抖

function fangdou(func, wait, immediate) {
    let timer
    return function () {
      let _this = this
      let arg = arguments
      // if (timer) {
      clearTimeout(timer)
      // }
      if (immediate) {
        let code = !timer
        timer = setTimeout(function () {
          timer = null
        }, wait)
        if (code) {
          func.apply(_this, arg)
        }
      } else {
        timer = setTimeout(function () {
          func.apply(_this, arg)
        }, wait)
      }
    }
  }

树形数据

function formatTreeData (data) {
  let parent = data.filter(item => item.pid === 0)
  let children = data.filter(item1 => item1 !== 0)
  toTreeData(parent, children)
  //封装递归函数
  function toTreeData (parent, children) {
    //循环父级
    parent.forEach(item2 => {
      //循环子级
      children.forEach((item3, index) => {
        if (item2.id === item3.pid) {
          //children是一个引用类型,需要深拷贝,否则会影响使用了children的地方
          let _children = JSON.parse(JSON.stringify(children))
          //如果该循环项为parent的子级,删除该项,进行下一次递归
          _children.splice(index, 1)
          //递归
          toTreeData([item3], _children)
          if (item2.children) {
            item2.children.push(item3)
          } else {
            item2.children = [item3]
          }
        }
      })
    })
  }
}