防抖、节流、深拷贝
防抖debounce
在事件被触发n秒后执行,如果在这n秒内又被触发,则重新计时。业务场景比如远程搜索;按钮提交,防止多次提交只执行最后一次;
//防抖函数
const debounce = (fn,delay)=>{
let timer = null;
return (...args)=>{
clearTimeout(timer);
timer = setTimeout(()=>{
fn.apply(this,args)
},delay);
};
};
在vue中实现demo:
1.在data中定义timer
2.methods
// 防抖函数
debounce(fn,delay){
return (...args)=>{
clearTimeout(this.timer)
this.timer = setTimeout(()=>{
fn.apply(this,args)
},delay)
}
},
remoteSearch(){
console.log('远程搜索:'+this.updateParam.deviceSn)
},
// vantweapp的van-field @input="getDeviceSn"
getDeviceSn(e) {
this.updateParam.deviceSn = e.detail
this.debounce(this.remoteSearch,1500)()
},
节流throttle
规定在一单位时间内,只能触发一次函数。如果这个单位时间内触发多次函数,只有一次生效。类似游戏里的技能CD
const throttle = (fn,delay = 500) =>{
let flag = true;
return (...args) =>{
if (!flag) return;
flag = false;
setTimeout(() => {
fn.apply(this,args)
},delay);
};
};
深拷贝deepclone、浅拷贝
浅拷贝指修改B对象的属性和方法会影响到A对象的属性和方法(对象直接赋值则是浅拷贝),深拷贝则不会
深拷贝方法
// es6
let b={...a}
// concat
let b = [].concat(a)
// for in
// 数组forEach
// json 局限性:1.无法实现函数、正则等特殊对象的克隆 2.会抛弃对象的constructor,所有的构造函数指向Object 3.对象有循环引用会报错
let b = JSON.parse(JSON.stringify(a))
驼峰转换
连字符转驼峰
let s1='get-element-by-id'
// 正则 function change(str){ return str.replace(/-\w/g,x=>{ return x.slice(1).toUpperCase() }) }
//
驼峰转连字符
let s2='getElementById'
function reverse(str){
return str.replace(/[A-Z]/g,x=>{
return '-'+x.toLowerCase()
})
}

浙公网安备 33010602011771号