1.防抖函数
function debounce ( fn, delay ) {
let timer = null
return function ( ) {
clearTimeout ( timer)
timer = setTimeout ( function ( ) {
fn . apply ( this , arguments)
} , delay)
}
}
btn. addEventListener (
'click' ,
debounce ( function ( ) {
console. log ( '点击了' )
} , 1000 )
)
2.节流函数
< button> 点击< / button>
function throttle ( fn, delay ) {
let timer = null
return function ( ) {
if ( ! timer) {
timer = setTimeout ( function ( ) {
fn . apply ( this , arguments)
timer = null
} , delay)
}
}
}
let btn = document. querySelector ( 'button' )
btn. addEventListener (
'click' ,
throttle ( function ( ) {
console. log ( '点击了' )
} , 1000 )
)
3.数据扁平化处理函数
function flat ( arr ) {
return arr. reduce ( ( prev, curr ) => {
return prev. concat ( curr)
} , [ ] )
}
let arr = [
[ 1 , 2 , 3 , 4 ] ,
[ 11 , 12 , 13 ]
]
console. log ( flat ( arr) )
4. 编写一个函数,首字母大写转换hello world
function toUpperCase ( str ) {
return str. replace ( / ^\w / , ( s ) => {
return s. toUpperCase ( )
}
)
}
console. log ( toUpperCase ( 'hello world' )
5. 已知有字符串 foo=”get-element-by-id”,写一个 function 将其 转化成驼峰表示法”getElementById”(必会)
let foo = 'get-element-by-id' ;
function camelize ( str ) {
return str. replace ( / -(\w) / g , function ( all, letter ) {
return letter. toUpperCase ( ) ;
} ) ;
}
console. log ( camelize ( foo) ) ;