Skip to content

js手写

浅拷贝实现

js
// 浅拷贝的实现;

function shallowCopy(object) {
  // 只拷贝对象
  if (!object || typeof object !== "object") return;

  // 根据 object 的类型判断是新建一个数组还是对象
  let newObject = Array.isArray(object) ? [] : {};

  // 遍历 object,并且判断是 object 的属性才拷贝
  for (let key in object) {
    if (object.hasOwnProperty(key)) {
      newObject[key] = object[key];
    }
  }

  return newObject;
}

深拷贝的实现

js
function deepCopy(object) {
  if (!object || typeof object !== "object") return;

  let newObject = Array.isArray(object) ? [] : {};

  for (let key in object) {
    if (object.hasOwnProperty(key)) {
      newObject[key] =
        typeof object[key] === "object" ? deepCopy(object[key]) : object[key];
    }
  }

  return newObject;
}

防抖

js
function debounce(func,delay) {
  let timer;
  return function{
    if(timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      func()
    },delay)
  }
}

节流

js
function throttle(func,delay) {
  let timer = null;
  return function{
    if(!timer) {
      timer = setTimeout(() => {
        fn;
        timer = null;
      },delay)
    }
  }
}

手写call

js