准备:深拷贝、防抖、节流

深拷贝

  • JSON 转换
JSON.parse(JSON.stringify([1,2,3,4]))

如果对象中有函数、undefind,无法拷贝出

  • 普通递归函数实现
function copy(data){
    if(!isObject(data)) return data
    let target = Array.isArray(data)?[]:{};
    for(let i in data){
        if(isObject(data[i])){
            target[i]  = copy(data[i])
        }else{
            target[i] = data[i]
        }
    }
    return target
}
function isObject(obj){
    return typeof obj === 'object' && obj!==null
}

防抖

防抖的原理就是:触发一个事件,在n秒后才执行,如果在n秒的时间内再次出发事件,以新事件的时间为准,总之,就是触发事件后,n秒内没有触发事件才执行

function debounce(fn,awit){
    var time = null
    return function(){
        let _this = this
        let arg = arguments
        clearTimeout(time)
        time = setTimeout(function(){
            fn.apply(_this,arg)
        },awit)
    }
}

节流

节流原理:
如果持续触发事件,每隔一段时间,只执行一次事件

function throttle(fn, awit) {
    let time = null
    return function(){
        let _this = this
        let arg = arguments
        let now = +new Date()
        if(now-time>awit){
            fn.apply(_this,arg)
            time = now
        }
    }
}

你可能感兴趣的:(准备:深拷贝、防抖、节流)