js常见的手写代码题

1. 手写new
function myNew(fn, ...args) {
  let obj = {} // 内部首先会先生成一个空对象
  obj.__proto__ = fn.prototype // 使空对象的隐式原型指向构造函数的显式原型
  let res = fn.apply(obj, args) // 把函数中的this指向该对象并执行构造函数中的语句
  return res instanceof Object ? res : obj // 返回该对象实例
}
2. 手写instanceOf
function myInstanceOf(instance, target) {
  if (!instance || !target) {
    return
  }
  if (typeof target !== 'function') {
    throw Error('target不是一个构造函数!')
  }
  let proto = Object.getPrototypeOf(instance) // 获取实例的原型
  let targetProto = target.prototype
  while (true) {
    if (!proto) return false
    if (proto === targetProto) return true
    proto = proto.getPrototypeOf(proto)
  }
}
3. 手写深拷贝
function deepClone(obj) {
  if (typeof obj === 'object') {
    const temp = Array.isArray(obj) ? [] : {}
    for (let k in obj) {
      temp[k] = deepClone(obj[k])
    }
    return temp
  } else {
    return obj
  }
}
4. 手写apply、call、bind
let obj = { name: 'zhangsan' }
function testFn(age, job) {
  console.log(this.name)
  console.log(age)
  console.log(job)
}

// 手写call
Function.prototype.myCall = function (context, ...args) {
  context = context || window // 如果没有传入上下文,则默认为全局对象 window,context是传入的obj对象
  context.fn = this // 将当前函数作为上下文的方法,这里的this指的是函数testFn,因为是testFn调用的myCall
  const result = context.fn(...args) // 使用调用函数,并传入参数
  delete context.fn // 删除临时添加的方法
  return result // 返回函数执行结果
}
testFn.myCall(obj, '18', '攻城狮')

// 手写apply
Function.prototype.myApply = function (context, argsArray) {
  context = context || window // 如果没有传入上下文,则默认为全局对象 window
  context.fn = this // 将当前函数作为上下文的方法
  const result = context.fn(...argsArray) // 使用展开运算符调用函数,并传入参数数组
  delete context.fn // 删除临时添加的方法
  return result // 返回函数执行结果
}
testFn.myApply(obj, ['18', '攻城狮'])

/**
 * 手写bind方法
 * bind不会像call 和 apply一样在调用的时候就执行,而是返回一个函数,该函数可以在稍后的调用中以特定的上下文和参数
 */
Function.prototype.myBind = function (context, ...args) {
  const self = this // 缓存当前函数
  return function (...args2) {
    return self.apply(context, [...args, ...args2]) // 调用 apply 方法,并合并传入的参数
  }
}
let res = testFn.bind(obj, '18', '攻城狮')
console.log(res())
5. 手写fliter、find函数
let arr = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }]
// filter函数
let r1 = arr.filter((item, index) => {
  return item.id === 1
})
// 手写filter函数
function Filter(arr, callback) {
  let res = [] // 定义空数组接收满足条件的数据
  arr.forEach((item, index) => {
    let temp = callback(item, index)
    if (temp) {
      res.push(temp)
    }
  })
  return res
}
let r = Filter(arr, (item, index) => item.id > 1)

// find函数
arr.find((item) => item.id === 1)
// 手写find函数
function Find(arr, callback) {
  for (let i = 0; i < arr.length; i++) {
    let res = callback(arr[i], i)
    if (res) {
      return arr[i]
    }
  }
}
let f = Find(arr, (item, index) => item.id === 2)
6. 数组去重
let arrObj = [
  { name: '小红', id: 1 },
  { name: '小黄', id: 4 },
  { name: '小绿', id: 3 },
  { name: '小青', id: 1 },
  { name: '小蓝', id: 4 }
]
        
// 方法1 空对象 + 数组
function repeat1(arr) {
  let res = []
  let obj = {}
  for (let k in arr) {
    if (!obj[arr[k].id]) {
      res.push(arr[k])
      obj[arr[k].id] = true
    }
  }
  return res
}
console.log(repeat1(arrObj))

// Map去重
function repeat2(arr) {
  let map = new Map()
  for (let item of arr) {
    if (!map.has(item.id)) {
      map.set(item.id, item)
    }
  }
  return [...map.values()]
}
console.log(repeat2(arrObj))

// includes 去重
function repeat3(arr) {
  let temp = []
  arr.forEach((item, index) => {
    temp.push(item.id)
    if (temp.includes(item.id)) {
      arr.splice(index, 1)
    }
  })
  return arr
}
console.log(repeat3(arrObj))
7. 防抖和节流
// 防抖
function debounce(fn, delay = 1000) {
  let timer = null
  return function (...args) {
    console.log(timer)
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this, args)
      timer = null
    }, delay)
  }
}
// 节流(定时器版本)
function throttle(fn, delay = 1000) {
  let timer = null
  return function (...args) {
    if (timer) return
    timer = setTimeout(() => {
      fn.apply(this, args)
      timer = null
    }, delay)
  }
}
// 节流(非定时器版本)
function throttle(fn, delay = 1000) {
  let lastTime = 0
  return function (...args) {
    let now = Date.now() // 当前时间的时间戳
    if (now - lastTime >= delay) {
      fn.apply(this, args)
      lastTime = now // 更新上次执行的时间戳
    }
  }
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值