手写代码
1. 函数的call() / apply() / bind()
Function.prototype.call = function(obj,...args) {
if(obj === null || obj === undefined ){
return this(...args)
}
obj.tempFn = this
const result = obj.tempFn(...args)
delete obj.tempFn
return result
}
Function.prototype.apply = function (obj,args) {
if(obj === null || obj === undefined ){
return this(...args)
}
obj.tempFn = this
const result = obj.tempFn(...args)
delete obj.tempFn
return result
}
2. 手写防抖节流
function throttle (callback,time){
let start = 0
return function (e) {
const current = Date.now()
if(current - start > time){
callback.call(e.target,e)
start = current
}
}
}
function debounce (callback , time){
return function(e){
if(callback.timeoutId){
clearTimeout(callback.timeoutId)
}
callback.timeoutId = setTimeout(() => {
callback.call(e.target,e)
delete callback.timeoutId
},time)
}
}
3. 数组去重
function unique2 (array) {
const arr = []
const obj = {}
array.forEach(item => {
if (!obj[item]) {
obj[item] = true
arr.push(item)
}
})
return arr
}
function unique3 (array) {
return [...new Set(array)]
}
4. 数据扁平化
function fn (arr){
const res = arr.map(item => Array.isArray(item)? fn(item):item )
return res
}
fn(arr)
5. 深拷贝
function deepClone1 (data){
return JSON.parse(JSON.stringify(data))
}
function deepClone2 (data){
const type = getType(target)
if (type==='Object' || type==='Array') {
const cloneTarget = type === 'Array' ? [] : {}
for (const key in target) {
if (target.hasOwnProperty(key)) {
cloneTarget[key] = deepClone2(target[key])
}
}
return cloneTarget
} else {
return target
}
}