Skip to content

手写代码面试题精讲

手写代码是面试里最"硬"的环节:没有沟通余地,写不出来就是写不出来。这类题的准备策略和八股完全不同——看懂不等于会写,每个题必须落到编辑器里敲到不看笔记能写出来。本篇覆盖 15 个高频手写题,每题给"可直接背写的标准答案"和"面试官追问点"。

通用建议:写之前先问一句"需要考虑边界情况吗"(比如防抖要不要 leading 选项),既确认需求又展示工程意识;写完主动说复杂度——这是区分"刷过题"和"工程师"的细节。

1. 手写 new

js
function myNew(constructor, ...args) {
  // 1. 创建空对象,原型链连到构造函数 prototype
  const obj = Object.create(constructor.prototype);
  // 2. 以 obj 为 this 调用构造函数
  const result = constructor.apply(obj, args);
  // 3. 构造函数返回对象则用之,否则用新建的 obj
  return result !== null && (typeof result === 'object' || typeof result === 'function')
    ? result
    : obj;
}

// 测试
function Person(name) { this.name = name; }
Person.prototype.say = function () { return `I am ${this.name}`; };
const p = myNew(Person, 'Tom');
console.log(p.name, p.say(), p instanceof Person); // Tom / I am Tom / true

追问:构造函数返回原始类型会怎样?(忽略,仍返回 obj——代码里 typeof result === 'object' || 'function' 之外都返回 obj)ES6 class 能用这个吗?(class 有 [[Call]] 限制不能直接调,但 myNew 内部是 .apply——会抛 TypeError,真实 class 场景用 Reflect.construct)

2. 手写 call / apply / bind

js
// call:上下文 + 逐个参数
Function.prototype.myCall = function (context, ...args) {
  context = context == null ? globalThis : Object(context);
  const key = Symbol('fn'); // Symbol 防止覆盖上下文已有属性
  context[key] = this;
  const result = context[key](...args);
  delete context[key];
  return result;
};

// apply:参数数组
Function.prototype.myApply = function (context, args = []) {
  context = context == null ? globalThis : Object(context);
  const key = Symbol('fn');
  context[key] = this;
  const result = context[key](...args);
  delete context[key];
  return result;
};

// bind:返回新函数 + 预设参数 + 可被 new
Function.prototype.myBind = function (context, ...bindArgs) {
  const fn = this;
  if (typeof fn !== 'function') {
    throw new TypeError('Function.prototype.bind called on non-function');
  }
  const bound = function (...callArgs) {
    // new 调用时 this 是 bound 的实例,context 失效
    const thisArg = this instanceof bound ? this : Object(context || globalThis);
    return fn.apply(thisArg, bindArgs.concat(callArgs));
  };
  bound.prototype = Object.create(fn.prototype); // 保持原型链
  return bound;
};

追问:为什么 bind 的函数还能被 new?(ES6 规范:bound function 被 new 时忽略绑定的 this,用新创建的对象——this instanceof bound 就是判断这个)Symbol 做临时 key 有什么好处?(不会污染目标对象,不会撞上已有属性名)

3. 手写防抖与节流

js
// 防抖:停止触发 delay 后才执行
function debounce(fn, delay = 300, { leading = false, trailing = true } = {}) {
  let timer = null;
  return function (...args) {
    const invoked = leading && !timer; // leading:首次立即执行
    if (timer) clearTimeout(timer);
    if (invoked) fn.apply(this, args);
    timer = setTimeout(() => {
      timer = null;
      if (trailing && !invoked) fn.apply(this, args);
    }, delay);
  };
}

// 节流:固定频率,时间戳版(首次立即 + 末尾不一定执行)
function throttle(fn, interval = 300) {
  let last = 0;
  return function (...args) {
    const now = Date.now();
    if (now - last >= interval) {
      last = now;
      fn.apply(this, args);
    }
  };
}

追问:时间戳节流的问题?(停止触发后如果最后一次没到间隔,末尾那次丢失——定时器版能补 trailing;lodash 是两者结合)React 里怎么用?(useMemo 缓存 + 组件卸载时 debounced.cancel——lodash 版带 cancel)

4. 手写深拷贝

js
function deepClone(target, hash = new WeakMap()) {
  if (target === null || typeof target !== 'object') return target;
  if (target instanceof Date) return new Date(target);
  if (target instanceof RegExp) return new RegExp(target);
  // 循环引用:已拷贝过直接返回映射
  if (hash.has(target)) return hash.get(target);

  const clone = Array.isArray(target) ? [] : {};
  hash.set(target, clone);
  for (const key in target) {
    if (Object.prototype.hasOwnProperty.call(target, key)) {
      clone[key] = deepClone(target[key], hash);
    }
  }
  return clone;
}

追问:WeakMap 解决什么?(循环引用——a.self = a 的场景没有它栈溢出)JSON.parse(JSON.stringify()) 的四个坑?(undefined/函数丢失、循环引用抛错、Date 变字符串、正则变空对象——所以它只适合纯 JSON 数据)还有更好的方案吗?(structuredClone() 原生,生产首选)

5. 手写 Promise(标准版)

面试重灾区,给出可背写的完整实现(A+ 规范核心):

js
const PENDING = 'pending', FULFILLED = 'fulfilled', REJECTED = 'rejected';

class MyPromise {
  constructor(executor) {
    this.state = PENDING;
    this.value = undefined;
    this.reason = undefined;
    this.onFulfilledCallbacks = [];
    this.onRejectedCallbacks = [];

    const resolve = (value) => {
      if (this.state !== PENDING) return; // 状态不可逆
      if (value instanceof MyPromise) return value.then(resolve, reject);
      this.state = FULFILLED;
      this.value = value;
      this.onFulfilledCallbacks.forEach((cb) => cb());
    };
    const reject = (reason) => {
      if (this.state !== PENDING) return;
      this.state = REJECTED;
      this.reason = reason;
      this.onRejectedCallbacks.forEach((cb) => cb());
    };

    try {
      executor(resolve, reject);
    } catch (err) {
      reject(err);
    }
  }

  then(onFulfilled, onRejected) {
    onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : (v) => v;
    onRejected = typeof onRejected === 'function' ? onRejected : (r) => { throw r; };

    const promise2 = new MyPromise((resolve, reject) => {
      const runFulfilled = () => {
        queueMicrotask(() => { // then 回调异步执行
          try {
            const x = onFulfilled(this.value);
            resolvePromise(promise2, x, resolve, reject);
          } catch (e) { reject(e); }
        });
      };
      const runRejected = () => {
        queueMicrotask(() => {
          try {
            const x = onRejected(this.reason);
            resolvePromise(promise2, x, resolve, reject);
          } catch (e) { reject(e); }
        });
      };
      if (this.state === FULFILLED) runFulfilled();
      else if (this.state === REJECTED) runRejected();
      else { // pending:入队等状态落定
        this.onFulfilledCallbacks.push(runFulfilled);
        this.onRejectedCallbacks.push(runRejected);
      }
    });
    return promise2;
  }

  catch(onRejected) { return this.then(null, onRejected); }

  static resolve(v) { return v instanceof MyPromise ? v : new MyPromise((r) => r(v)); }
  static reject(r) { return new MyPromise((_, rej) => rej(r)); }
  static all(list) {
    return new MyPromise((resolve, reject) => {
      const results = [];
      let count = 0;
      list.forEach((p, i) => {
        MyPromise.resolve(p).then((v) => {
          results[i] = v;
          if (++count === list.length) resolve(results);
        }, reject);
      });
    });
  }
}

// thenable 递归展开:then 返回值可能又是 Promise
function resolvePromise(p2, x, resolve, reject) {
  if (p2 === x) return reject(new TypeError('Chaining cycle'));
  if (x instanceof MyPromise) {
    x.then(resolve, reject); // 注意:thenable 也要处理(略去完整 thenable 分支)
  } else {
    resolve(x);
  }
}

追问:为什么要 queueMicrotask?(then 回调必须异步——同步执行会破坏 Promise 的"最终一致性"语义)resolvePromise 里防 p2 === x 是防什么?(then 返回自己造成死循环)all 里为什么结果按下标存?(保证输出顺序和输入一致,与完成先后无关)

6. 手写数组去重 / 扁平 / 最值

js
// 去重:Set(SameValueZero——NaN 也能去)
const unique = (arr) => [...new Set(arr)];

// 扁平:reduce 递归版(可指定深度)
function flat(arr, depth = 1) {
  return depth > 0
    ? arr.reduce((acc, cur) =>
        acc.concat(Array.isArray(cur) ? flat(cur, depth - 1) : cur), [])
    : arr.slice();
}

// 最值:reduce 比 Math.max(...arr) 稳(后者大数组爆栈)
const max = (arr) => arr.reduce((a, b) => (b > a ? b : a));

追问:Math.max(...arr) 什么时候炸?(数组长度超过引擎参数上限(约 12 万)——大数组必须 reduce 或循环)对象数组按字段去重怎么写?(Map 缓存 key:const seen = new Map(); arr.filter(x => !seen.has(x.id) && seen.set(x.id, 1)))

7. 手写发布订阅模式

js
class EventEmitter {
  constructor() { this.events = Object.create(null); }

  on(event, cb) {
    (this.events[event] || (this.events[event] = [])).push(cb);
    return this; // 链式
  }

  once(event, cb) {
    const wrapper = (...args) => { this.off(event, wrapper); cb(...args); };
    return this.on(event, wrapper);
  }

  emit(event, ...args) {
    (this.events[event] || []).forEach((cb) => cb(...args));
    return this;
  }

  off(event, cb) {
    if (!cb) { delete this.events[event]; return this; } // 无 cb 清空该事件
    this.events[event] = (this.events[event] || []).filter((f) => f !== cb);
    return this;
  }
}

追问:once 为什么包 wrapper?(执行前先移除自己——注意 wrapper 引用要能 off 对,所以 once 注册的是 wrapper 不是原 cb) emit 时遍历中 off 当前事件会漏吗?(先 slice() 拷贝再遍历是防御习惯——原版会跳过下一个;面试里提一句是加分项)

8. 手写 instanceof

js
function myInstanceof(instance, constructor) {
  let proto = Object.getPrototypeOf(instance);
  const target = constructor.prototype;
  while (proto !== null) {
    if (proto === target) return true;
    proto = Object.getPrototypeOf(proto);
  }
  return false;
}

追问:为什么 instanceof 跨 iframe 会失效?(两个 iframe 的 Array 是不同的构造函数对象,prototype 引用不同——用 Array.isArray 或 Object.prototype.toString 跨 realm)

9. 手写柯里化

js
function curry(fn) {
  const next = (...args) =>
    args.length >= fn.length
      ? fn(...args)
      : (...rest) => next(...args, ...rest);
  return next;
}

// 测试
const add = (a, b, c) => a + b + c;
const curriedAdd = curry(add);
curriedAdd(1)(2)(3); // 6
curriedAdd(1, 2)(3);  // 6

追问:为什么用 fn.length判断?(函数的 length 是第一个默认值参数之前的形参个数——(a, b, c = 1) => {} 的 length 是 2,边界要小心)

10. 手写 LRU 缓存

js
class LRUCache {
  constructor(capacity) {
    this.capacity = capacity;
    this.map = new Map(); // Map 保持插入顺序,天然适合 LRU
  }
  get(key) {
    if (!this.map.has(key)) return -1;
    const value = this.map.get(key);
    this.map.delete(key);
    this.map.set(key, value); // 重新插入到末尾 = 最新使用
    return value;
  }
  put(key, value) {
    if (this.map.has(key)) this.map.delete(key);
    this.map.set(key, value);
    if (this.map.size > this.capacity) {
      this.map.delete(this.map.keys().next().value); // 删除最旧(第一个)
    }
  }
}

追问:为什么 Map 比对象好?(保序 + 任意类型键 + O(1) 删首——对象做不到 O(1) 删"第一个插入的键")双向链表版和 Map 版的取舍?(面试写 Map 版够了;追问链表版是考察"能不能手写带头尾哨兵节点的链表")

11. 手写定时执行与竞态处理

js
// 限制并发:Promise 池
function asyncPool(poolLimit, tasks) {
  const results = [];
  let i = 0;
  const run = async () => {
    if (i >= tasks.length) return;
    const cur = i++;
    results[cur] = await tasks[cur]();
    await run();
  };
  const workers = Array.from({ length: Math.min(poolLimit, tasks.length) }, run);
  return Promise.all(workers).then(() => results);
}

追问:这个实现和 Promise.all 分片有什么区别?(pool 是"同时最多 n 个",分片是"每批 n 个等齐再下一批"——前者吞吐更好)

12. 手写 sleep 与超时控制

js
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

// 给 Promise 加超时
function withTimeout(promise, ms) {
  return Promise.race([
    promise,
    sleep(ms).then(() => Promise.reject(new Error(`Timeout after ${ms}ms`))),
  ]);
}

追问:race 超时后原请求会停吗?(不会——Promise 没有取消语义,请求继续跑;要真取消用 AbortController:setTimeout(() => controller.abort(), ms))AbortSignal.timeout(ms) 是现代内置方案

13. 手写 EventBus 的 useEventEmitter(React 版)

框架结合题,考察 hooks 熟练度:

jsx
function useEventEmitter() {
  const emitter = useRef(new EventEmitter()).current; // ref 保持跨渲染单例
  useEffect(() => () => emitter.off(), [emitter]); // 卸载全清
  return emitter;
}

追问:为什么 useRef(new EventEmitter()) 不用 useMemo?(ref 初始化只跑一次;useMemo 理论上可被重算且语义是"缓存"不是"单例"——ref 更诚实)清理为什么用 off() 无参版?(组件可能注册了多个事件,逐个 off 要记账——批量清空更稳)

14. 手写排序:快排(最常考)

js
function quickSort(arr) {
  if (arr.length <= 1) return arr;
  const pivot = arr[arr.length - 1];
  const left = [], right = [];
  for (let i = 0; i < arr.length - 1; i++) {
    (arr[i] < pivot ? left : right).push(arr[i]);
  }
  return [...quickSort(left), pivot, ...quickSort(right)];
}

// 原地版(省内存,面试官更想看到)
function quickSortInPlace(arr, low = 0, high = arr.length - 1) {
  if (low >= high) return arr;
  let i = low, j = high;
  const pivot = arr[low];
  while (i < j) {
    while (i < j && arr[j] >= pivot) j--;
    while (i < j && arr[i] <= pivot) i++;
    [arr[i], arr[j]] = [arr[j], arr[i]];
  }
  arr[low] = arr[i];
  arr[i] = pivot;
  quickSortInPlace(arr, low, i - 1);
  quickSortInPlace(arr, i + 1, high);
  return arr;
}

追问:快排的最坏复杂度什么时候出现?(每次 pivot 都取到最值——已排序数组 + 固定取末尾/开头就是 O(n²);随机 pivot 或三数取中规避)稳定性?(不稳定——[3a, 3b] 分区时相对顺序可能变;要稳定用归并)

15. 其他出现频率高的五道

数组转树(扁平转层级):

js
function listToTree(list) {
  const map = new Map(list.map((n) => [n.id, { ...n, children: [] }]));
  const root = [];
  for (const node of map.values()) {
    if (node.parentId && map.has(node.parentId)) {
      map.get(node.parentId).children.push(node);
    } else {
      root.push(node);
    }
  }
  return root;
}

对象扁平化转嵌套:

js
function flatToNested(obj) {
  const result = {};
  for (const [path, value] of Object.entries(obj)) {
    const keys = path.split('.');
    keys.reduce((acc, key, i) => {
      acc[key] = i === keys.length - 1 ? value : (acc[key] || {});
      return acc[key];
    }, result);
  }
  return result;
}

乱序数组找第 K 大(快速选择,O(n) 平均):

js
function findKthLargest(nums, k) {
  const target = nums.length - k; // 第 k 大 = 升序下标 n-k
  let lo = 0, hi = nums.length - 1;
  while (lo <= hi) {
    const p = partition(nums, lo, hi);
    if (p === target) return nums[p];
    if (p < target) lo = p + 1; else hi = p - 1;
  }
}

千分位格式化(考虑小数和负数):

js
const format = (n) => {
  const [int, dec] = String(n).split('.');
  const sign = int.startsWith('-') ? '-' : '';
  const abs = sign ? int.slice(1) : int;
  const withComma = abs.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
  return sign + withComma + (dec ? `.${dec}` : '');
};

异步串行执行任务数组:

js
async function runSeries(tasks) {
  for (const task of tasks) {
    await task(); // for...of 才串行;forEach(async) 是并发
  }
}

准备策略:手写题怎么练

  1. 第一遍:按篇过,每题在编辑器敲到不看答案写出来——注意是"写出来"不是"看懂"
  2. 第二遍:限时——简单题(防抖、去重)3 分钟,中等题(Promise、深拷贝)15 分钟,难题(快排、LRU)20 分钟
  3. 第三遍:模拟白板/在线编程环境(无提示、无补全、可运行不可调试)——很多人看得懂但白板写不出分号和括号
  4. 面试中:先问需求(边界、参数含义)→ 说思路 → 写 → 自测(口头跑用例)→ 说复杂度。主动测试和说复杂度是强烈加分信号

自查清单

  • [ ] 不看书写出:new / call / bind / 防抖 / 节流 / 深拷贝
  • [ ] 不看书写出:Promise 完整版(含 then 链和静态方法)
  • [ ] 不看书写出:LRU / 快排(原地版)/ 数组转树
  • [ ] 能解释每个实现的边界处理(循环引用、状态不可逆、尾差)

最后一篇是场景设计题——开放题的框架比答案重要。

CTO Plus技术栈 Version 1.0.20261024-12