手写代码题

重写数组方法
  • push(从数组后面添加一项或多项)
Array.prototype.push = function(){
    for(var i=0,l=arguments,length;i<l;i++>){
        this[this.length-1] = arguments(i);
    }
    return this.length;
}
  • pop(删除最后一项,并返回删除项)
Array.prototype.pop = function(){
    var item = this[this.length-1];
    if(this.length>0){
        this.length = this.length-1;
    }
    return item;
}
  • shift从前面删除一项,返回删除项
Array.prototype.shift = function(){
    var item = this[0]; 
    for(var i=1,l=this.length;i<l;i++>){
        this[i-1] = this[i];
    }
    this.length = this.length-1;
    return item;
}
  • unshift 从前面增加一项或多项
//数组先后移,再插入
Array.prototype.unshift = function(){
    for(var i =0;i<this.length;i++>){
        this[i+arguments.length] = this[i];
    }

    for(var i=0;i<arguments.length;i++){
        this[i] = arguments[i];
    }
    return 

}

  • fitler
Array.prototype.filter = function(handler){
    var newArr = [];
    this.forEach(function(item,index,this){
        if(handler(item,index,this)){
            newArr(newArr.length-1) = item;
        }
    })
    return newArr;
}
深拷贝
  • 简单深拷贝
let newObj = JSON.parse(JSON.stringfy(obj));
//存在问题:不能拷贝原型上属性和方法
  • 递归深拷贝
function deepClone(obj){
 var newObj = Array.isArray(obj)?[]:{};
 if(typeof obj!='object'){
     return obj;
 }
 for(var item in obj){
    if(obj.hasOwnPropty(item)){
        newObj[item] = typeof(obj[item])='object'?arguments.callee(item):obj[item];
    }
 }
 return newObj;

}

函数节流/函数防抖
  • 函数节流

防止重复提交,一段时间内多次触发的事件只执行一次(点击事件)

function throtte(handler,wait){
    let preTime = 0;
    return function(){
    let now = date.now();
        if(now-preTime>wait){
            handler.call(this);
            preTime = now;
        }
    }
}

oBtn.onclick = throtte(function(){
    console.log('1s内只执行一次')
},1000)

  • 函数防抖

延迟执行,连续触发的事件。只执行一次(电梯)

functon debunce(handler,wait){
    var timer = null;
    return function(){
        if(timer){
        clearTimeout(timer);
        }
        timer  =setTimeout(function(){
            handler.call(this);
        },wait)
    }

}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值