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

  • 搜索输入联想 → 防抖
  • 滚动加载更多 → 节流
  • 按钮防重复点击 → 防抖
  • 拷贝多层对象 → 深拷贝
相关推荐
zxna12 小时前
前端直连oss分片上传文件,断点续传
前端
Southern Wind12 小时前
Vue 3 + Socket.io 实时聊天项目完整开发文档
前端·javascript·vue.js
甄心爱学习12 小时前
【项目实训(个人4)】
前端·vue.js·python
轮子大叔12 小时前
HTML入门
前端·html
skilllite作者12 小时前
SkillLite 技术演进笔记:Workspace、沙箱与进化
java·开发语言·前端·笔记·安全·agentskills
qq_4198540512 小时前
clip-path绘制倾斜角裁剪的矩形占比条;基于svg实现仪表盘弧线占比图。
前端·javascript·vue.js
m0_7381207212 小时前
渗透基础知识ctfshow——Web应用安全与防护(完结:第八章)
前端·python·sql·安全·web安全·网络安全
克里斯蒂亚诺更新12 小时前
uniapp适配H5和Android-apk实现获取当前位置经纬度并调用接口
android·前端·uni-app
宁&沉沦13 小时前
前端开发专用的 Cursor 四大模式「快捷切换 + 指令模板」,直接复制就能用,覆盖 90% 日常场景
前端·编辑器
Cloud Traveler13 小时前
用Calibre-Web把NAS上的电子书管起来:部署、配置与远程访问实战
前端