Skip to content

工具函数

一、深拷贝

js
function deepClone(obj) {
    if (typeof obj !== 'object' || obj === null) {
        return obj; // 如果是基本类型或 null,直接返回
    }
    let result = Array.isArray(obj) ? [] : {};
    for (let key in obj) {
        if (obj.hasOwnProperty(key)) { // 只克隆对象自身的属性
            result[key] = deepClone(obj[key]);
        }
    }
    return result;
}

obj.hasOwnProperty(key)的作用是确保只克隆对象自身的属性,而不会复制从原型链继承的属性。

例如:

js
const parent = { a: 1 };
const child = Object.create(parent);
child.b = 2;

// 如果不加 hasOwnProperty,会复制原型链上的属性
for (let key in child) {
    console.log(key); // 输出 'b' 和 'a'(继承自 parent)
}

如果 deepClone不加 hasOwnProperty判断,克隆后的对象会包含 child和 parent的所有属性,这通常不是我们想要的。

二、防抖

核心思想

连续触发事件后,只在最后执行一次。

主要应用

  • 搜索框输入联想
  • 表单验证

简单实现:

js
function debounce(fn, wait) {
    let timeoutId;

    return function (...args) {

      clearTimeout(timeoutId);

      timeoutId = setTimeout(() => {
        fn.apply(this, args)
      }, wait);
    }
}

三、节流

核心思想

在一定时间间隔内,只执行一次。

主要应用

  • 窗口调整大小
  • 滚动事件

简单实现:

js
function throttle(fn, wait) {
    let lastTime = 0;

    return function (...args) {
      const now = Date.now();
      if (now - lastTime >= wait) {
        lastTime = now;
        fn.apply(this, args);
      }
    }
}