前端面试手写核心 Cheat Sheet(终极精简版)

背会这一页,面试手写题直接稳过!


1. 防抖 & 节流

防抖(debounce)

  • 场景:搜索输入、窗口 resize、按钮防重复点击
  • 核心:频繁触发 → 只执行最后一次
js 复制代码
function debounce(fn, delay) {
  let timer = null
  return function (...args) {
    clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this, args)
    }, delay)
  }
}

节流(throttle)

  • 场景:滚动加载、高频点击、鼠标移动
  • 核心:频繁触发 → 每隔一段时间执行一次
js 复制代码
function throttle(fn, delay) {
  let lastTime = 0
  return function (...args) {
    const now = Date.now()
    if (now - lastTime >= delay) {
      fn.apply(this, args)
      lastTime = now
    }
  }
}

2. 数组去重

js 复制代码
function unique(arr) {
  return [...new Set(arr)]
}

3. call / apply / bind

myCall

js 复制代码
Function.prototype.myCall = function (context, ...args) {
  context = context || window
  const fn = Symbol()
  context[fn] = this
  const result = context[fn](...args)
  delete context[fn]
  return result
}

myApply

js 复制代码
Function.prototype.myApply = function (context, args) {
  context = context || window
  args = args || []
  const fn = Symbol()
  context[fn] = this
  const result = context[fn](...args)
  delete context[fn]
  return result
}

myBind

js 复制代码
Function.prototype.myBind = function (context) {
  const self = this
  return function (...args) {
    return self.apply(context || window, args)
  }
}

4. 深拷贝(含循环引用)

js 复制代码
function deepClone(obj, map = new WeakMap()) {
  if (obj === null || typeof obj !== 'object') {
    return obj
  }
  if (map.has(obj)) return map.get(obj)

  const clone = Array.isArray(obj) ? [] : {}
  map.set(obj, clone)

  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      clone[key] = deepClone(obj[key], map)
    }
  }
  return clone
}

5. this 指向口诀

  1. obj.fun() → this = obj
  2. fun() → this = window / undefined
  3. call / apply / bind → 手动指定 this
  4. new → this = 新创建的对象

6. 场景速查

  • 搜索输入联想 → 防抖
  • 滚动加载更多 → 节流
  • 按钮防重复点击 → 防抖
  • 拷贝多层对象 → 深拷贝
相关推荐
Irene199114 分钟前
ElementPlus 与成熟后台框架对比:vue-element-plus-admin、vue-pure-admin等
前端·ui·框架·vue3
尘中客4 小时前
放弃 Echarts?前端直接渲染后端高精度 SVG 矢量图流的踩坑记录
前端·javascript·echarts·前端开发·svg矢量图·echarts避坑
FreeBuf_5 小时前
Chrome 0Day漏洞遭野外利用
前端·chrome
小彭努力中5 小时前
199.Vue3 + OpenLayers 实现:点击 / 拖动地图播放音频
前端·vue.js·音视频·openlayers·animate
2501_916007475 小时前
网站爬虫原理,基于浏览器点击行为还原可接口请求
前端·javascript·爬虫·ios·小程序·uni-app·iphone
前端大波5 小时前
Sentry 每日错误巡检自动化:设计思路与上手实战
前端·自动化·sentry
ZC跨境爬虫6 小时前
使用Claude Code开发校园交友平台前端UI全记录(含架构、坑点、登录逻辑及算法)
前端·ui·架构
慧一居士6 小时前
Vue项目中,何时使用布局、子组件嵌套、插槽 对应的使用场景,和完整的使用示例
前端·vue.js
Можно7 小时前
uni.request 和 axios 的区别?前端请求库全面对比
前端·uni-app
M ? A7 小时前
解决 VuReact 中 ESLint 规则冲突的完整指南
前端·react.js·前端框架