手写深拷贝
function deepClone(obj) {
if (obj === null) return null
if (typeof obj !== 'object') return obj
if (obj instanceof RegExp) {
return new RegExp(obj)
}
if (obj instanceof Date) {
return new Date(obj)
}
if (obj instanceof Function) {
return new Function(obj)
}
let newObj = new obj.constructor()
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
newObj[key] = deepClone(obj[key])
}
}
return newObj
}
手写判断数组
arr instanceof Array
arr.constructor === Array
Object.prototype.toString.call(arr)
通过 class 手写一个简易 jQuery
class JQuery {
constructor(selector) {
const result = document.querySelectorAll(selector)
const length = result.length
for (let i = 0; i < length; i++) {
this[i] = result[i]
}
this.length = length
this.selector = selector
}
get(index) {
return this[index]
}
each(fn) {
for (let i = 0; i < this.length; i++) {
const elem = this[i]
fn(elem)
}
}
on(type, fn) {
return this.each((elem) => {
elem.addEventListener(type, fn, false)
})
}
}
手写 bind 函数
Function.prototype.bind1 = function () {
const args = Array.prototype.slice.call(arguments)
const t = args.shift()
const self = this
return function () {
return self.apply(t, args)
}
}
手写防抖和节流
function debounce(fn, interval = 300) {
let timer = null
return function () {
clearInterval(timer)
timer = setTimeout(() => {
fn.apply(this, arguments)
}, interval)
}
}
function throttle(fn, interval = 300) {
let timer = null
return function () {
if (timer) {
return
}
timer = setTimeout(() => {
fn.apply(this, arguments)
timer = null
}, interval)
}
}
手写深度比较函数
function isObject(obj) {
if (typeof obj == 'object' && obj !== null) {
return true
}
}
function isEqual(obj1, obj2) {
if (!isObject(obj1) || !isObject(obj2)) {
return obj1 === obj2
}
if (obj1 === obj2) {
return true
}
const obj1KeyArr = Object.keys(obj1)
const obj2KeyArr = Object.keys(obj2)
if (obj1KeyArr.length !== obj2KeyArr.length) {
return false
}
for (let key in obj1) {
const res = isEqual(obj1[key], obj2[key])
if (!res) {
return false
}
}
return true
}
const obj1 = {
a: 100,
b: {
x: 100,
y: 200,
},
}
const obj2 = {
a: 100,
b: {
x: 100,
y: 200,
},
}
console.log(isEqual(obj1, obj2))
|