前端面试手写核心 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. 场景速查

  • 搜索输入联想 → 防抖
  • 滚动加载更多 → 节流
  • 按钮防重复点击 → 防抖
  • 拷贝多层对象 → 深拷贝
相关推荐
shmily麻瓜小菜鸡14 小时前
前端“伪防盗链”方案
前端·javascript·vue.js·bootstrap·echarts
mayaairi14 小时前
JS数组完全指南(含十大操作详解)
开发语言·前端·javascript
IT_陈寒15 小时前
Python的线程池把我CPU跑满了,原来少传了个参数
前端·人工智能·后端
喜欢的名字被抢了15 小时前
写-Chrome-扩展时踩过的那些-MV3-的坑
前端·chrome
网安老伯15 小时前
网络安全基础要点知识介绍(非常详细),零基础入门到精通,看这一篇就够了
运维·前端·网络协议·web安全·网络安全·职场和发展
wuqingshun31415915 小时前
springBoot是如何通过main方法启动web项目的?
前端·spring boot·后端
xxwl58515 小时前
HTML 小总结:从骨架到枝叶,系统掌握网页结构
前端·html
●VON15 小时前
鸿蒙 PC Markdown 编辑器 Bridge 协议:原生外壳与 Web 内核的状态同步
前端·华为·编辑器·harmonyos·鸿蒙
MrDJun15 小时前
分享一款免费实用的网页变动监控工具:PageWatch.tech
前端·javascript·vue.js
米码收割机15 小时前
【web】邻里悦站—社区便民服务平【独一无二】(源码+说明文档)
前端