重写数组方法
- 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)
}
}