1.手写节流
function throttle ( fn, delay = 100 ) {
let timer = null
return function ( ) {
if ( timer) {
return
}
timer = setTimeout ( ( ) => {
fn. apply ( this , arguments)
timer = null
} , delay)
}
}
div1. addEventListener ( ( 'drag' , throttle ( function ( e) {
console. log ( e. offsetX, e. offsetY)
} ) ) )
2.手写防抖函数
function debounce ( fn, delay= 500 ) {
let timer = null ;
return function ( ) {
if ( timer) {
clearTimeout ( timer)
}
timer = setTimeout ( ( ) => {
fn. apply ( this , arguments) ;
timer = null ;
} , delay)
}
}
input1. addEventListener ( 'keyup' , debounce ( ( ) => {
console. log ( input1. value) ;
} ) , 600 )
3.手写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 fn1 ( a, b, c) {
console. log ( 'this' , this )
console. log ( a, b, c)
return 'this is fn1'
}
const fn2 = fn1. bind1 ( { x: 100 } , 10 , 20 , 30 )
const res = fn2 ( )
console. log ( res)
4.手写递归
var arr = [ 1 , [ 2 , [ 3 , 4 ] ] ] ;
function flatten ( arr) {
var result = [ ] ;
for ( var i = 0 , len = arr. length; i < len; i++ ) {
if ( Array. isArray ( arr[ i] ) ) {
result = result. concat ( flatten ( arr[ i] ) )
}
else {
result. push ( arr[ i] )
}
}
return result;
}
console. log ( flatten ( arr) )
5.将数组转化为树形结构
/数组/
var menu_list = [ {
id: '1' ,
menu_name: '设置' ,
menu_url: 'setting' ,
parent_id: 0
} , {
id: '1-1' ,
menu_name: '权限设置' ,
menu_url: 'setting.permission' ,
parent_id: '1'
} , {
id: '1-1-1' ,
menu_name: '用户管理列表' ,
menu_url: 'setting.permission.user_list' ,
parent_id: '1-1'
} , {
id: '1-1-2' ,
menu_name: '用户管理新增' ,
menu_url: 'setting.permission.user_add' ,
parent_id: '1-1'
} , {
id: '1-1-3' ,
menu_name: '角色管理列表' ,
menu_url: 'setting.permission.role_list' ,
parent_id: '1-1'
} , {
id: '1-2' ,
menu_name: '菜单设置' ,
menu_url: 'setting.menu' ,
parent_id: '1'
} , {
id: '1-2-1' ,
menu_name: '菜单列表' ,
menu_url: 'setting.menu.menu_list' ,
parent_id: '1-2'
} , {
id: '1-2-2' ,
menu_name: '菜单添加' ,
menu_url: 'setting.menu.menu_add' ,
parent_id: '1-2'
} , {
id: '2' ,
menu_name: '订单' ,
menu_url: 'order' ,
parent_id: 0
} , {
id: '2-1' ,
menu_name: '报单审核' ,
menu_url: 'order.orderreview' ,
parent_id: '2'
} , {
id: '2-2' ,
menu_name: '退款管理' ,
menu_url: 'order.refundmanagement' ,
parent_id: '2'
}
]
/ 转换为树形结构/
const buildTree = ( arr) => {
tmp = { } ;
res = { } ;
for ( let i in arr) {
tmp[ arr[ i] . id] = arr[ i] ;
}
for ( let i in tmp) {
if ( tmp[ i] . parent_id) {
if ( ! tmp[ tmp[ i] . parent_id] . children) {
tmp[ tmp[ i] . parent_id] . children = new Object ( ) ;
}
tmp[ tmp[ i] . parent_id] . children[ tmp[ i] . id] = tmp[ i] ;
} else {
res[ tmp[ i] . id] = tmp[ i] ;
}
}
return res;
}
console. log ( buildTree ( menu_list) ) ;