手写常用的工具类函数
1. 防抖函数
function debounce ( fun, time ) {
let timeout = null
let timer = time || 500
return function ( ) {
clearTimeout ( timeout)
let args = arguments
let that = this
timeout = setTimeout ( function ( ) {
fun . apply ( that, args)
} , timer)
}
}
2. 节流函数
function throttle ( fun, time ) {
if ( time === null || time === undefined ) {
time = 1000
}
let lastTime = null ;
return function ( ) {
let newTime = + new Date ( )
if ( newTime - lastTime > time || ! lastTime) {
fun . apply ( this , arguments)
lastTime = newTime
}
}
}
3. 数组去重
1. 使用indexof ( )
let arr = [ 1 , 1 , 1 , 1 , 2 , 3 , 3 , 4 , 5 ]
let arr1 = [ ]
arr. forEach ( item => {
if ( arr1. indexOf ( item) === - 1 ) {
arr1. push ( item)
}
} )
console. log ( arr1)
2. 使用reduce ( )
let arr = [ 1 , 2 , 3 , 4 , 5 , 4 , 2 , 3 , 6 , 7 , 2 ]
let obj = { }
let arr1 = arr. reduce ( ( pre, cur ) => {
if ( obj[ cur] ) {
return pre
} else {
obj[ cur] = true
pre. push ( cur)
return pre
}
} , [ ] )
console. log ( arr1)
3. 使用set
let arr = [ 1 , 2 , 3 , 4 , 5 , 4 , 2 , 3 , 6 , 7 , 2 ]
let arr1 = [ ... new Set ( arr) ]
console. log ( arr1)
4. 使用filter ( )
let arr = [ 1 , 2 , 3 , 4 , 2 , 3 , 4 , 2 , 1 , 5 , 9 , 6 , 8 , 7 ] ;
let newArr = arr. filter ( ( item, index, array ) => array. indexOf ( item) === index) ;
console. log ( newArr)
4. 手写深拷贝
let arr = [ 1 , 2 , 3 , 4 , [ 5 , 6 , 7 , [ 8 , 9 ] ] ]
function deepClone ( val ) {
if ( typeof val !== 'object' || val === null ) {
return val
}
let result = Array. isArray ( val) ? [ ] : { }
for ( let i in val) {
if ( val. hasOwnProperty ( i) ) {
result[ i] = deepClone ( val[ i] )
}
}
return result
}
let arr1 = deepClone ( arr)
arr1[ 4 ] [ 0 ] = 10
console. log ( arr, arr1)
5. 多维数组扁平化
const arr= [ 1 , 2 , [ 3 , [ 4 , 5 ] ] ]
arr. flat ( Infinity )
const arr= [ 1 , 2 , [ 3 , 4 , [ 5 , 6 , 7 ] ] ] ;
let res= JSON . stringify ( arr) . replace ( / \[|\] / g , '' ) ;
res= JSON . parse ( ` [ ${ res} ] ` )
console. log ( res)
function flatten ( arr ) {
return arr. reduce ( ( pre, cur ) => {
return pre. concat ( Array. isArray ( cur) ? flatten ( cur) : cur)
} , [ ] )
}
6. 手写instanceof
function myInstanceof ( obj, constructor ) {
if ( typeof obj !== 'object' || obj === null ) {
return false ;
}
let proto = Object. getPrototypeOf ( obj) ;
while ( proto !== null ) {
if ( proto === constructor. prototype) {
return true ;
}
proto = Object. getPrototypeOf ( proto) ;
}
return false ;
}
function Person (
) { }
const person = new Person ( ) ;
console. log ( myInstanceof ( person, Person) ) ;
const obj = { } ;
console. log ( myInstanceof ( obj, Person) ) ;