2020年前端经典实用的面试题梳理

882 阅读1分钟

数组拍平

/**
 *
 * @param {arr} 多维数组
 * @return Array 树节点集合
 */
function flat(arr) {
  return arr.reduce((prev, item) => {
    return prev.concat(Array.isArray(item) ? flat(item) : item)
  }, [])
}

树节点广度优先遍历

/**
 *
 * @param {tree} 树节点
 * @return Array 树节点key集合
 */
function breadthFirstTraversal(tree) {
  const nodes = []
  const tempNodes = []
  if (tree) {
    tempNodes.push(tree)
    while (tempNodes.length) {
      const node = tempNodes.shift()
      nodes.push(node.key)
      if (node.left) {
        tempNodes.push(node.left)
      }
      if (node.right) {
        tempNodes.push(node.right)
      }
    }
  }
  return nodes
}

限制最大并发请求数

/**
 *
 * @param {arr} 请求的集合
 * @param {max} 最大并发数
 * @param {callback} 请求结束回调
 */
function maxFetch(arr, max = 3, callback) {
  let fetchNum = 0
  let result = []

  async function requeste(url) {
    if (!url) return
    fetchNum++
    const data = await fetch(url)
    console.log(data)
    result.push(data)
    fetchNum--
    requeste(arr.shift())
    if (!fetchNum) {
      callback && callback(result)
    }
  }

  while (fetchNum < max) {
    requeste(arr.shift())
  }
}

手写防抖

/**
 *
 * @param {callback} 事件触发的回调
 * @param {intervalTime} 间隔时间
 * return {function} 
 */
function thorttle(callback, intervalTime) {
  let eventTime = 0
  let timer = null
  return function() {
    const time = Date.now() // 当前事件触发的事件

    // 上次事件触发的时间
    if (!eventTime) {
      eventTime = time
    }

    // 清除上次延时定时器
    if (timer) {
      clearTimeout(timer)
    }

    // 当前事件触发时间距离上次触发时间的差值是否大于间隔时间
    const delay = time - eventTime
    if (delay >= intervalTime) {
      eventTime = time
      callback && callback(...arguments)
    } else {
      // 延时 intervalTime - delay 执行
      timer = setTimeout(() => {
        clearTimeout(timer)
        timer = null
        callback && callback(...arguments)
      }, intervalTime - delay)
    }
  }
}

手写apply

/**
 *
 * @param {content} 需要this绑定的对象
 * return {arg} content执行的参数
 */
Function.prototype.myApply = function(content, arg) {
  content.fn = this
  content.fn(...arg)
  delete content.fn
}

判断数据类型方法

/**
 *
 * @param {data} 数据
 * return {string} 数据类型字符串
 */
function getDataType(data) {
  const str = Object.prototype.toString.call(data)
  return str.replace(/^\[object (\S+)\]$/, '$1')
}

设计一套浏览器缓存机制

彻底理解浏览器的缓存机制

eventloop顺序题

JavaScript 事件循环

虚拟滚动实现原理

只显示可视区域内容,上下通过设置padding样式挤出高度,显示滚动条 vue-virtual-scroll-list 直接看源码理解的更深