防抖
// 防抖
function anti(fn,wait){
var timer=null;
return function(){
if(timer){
// 清除定时器
clearTimeout(timer);
}
let that = this;
let args = arguments;
timer = setTimeout(function(){
fn.apply(that,args)
},wait);
}
}
节流
// 节流
function throttle(fn,wait){
let timer=null;
return function(){
let that = this;
let args = arguments;
if(!timer){
timer = setTimeout(function(){
fn.apply(that,args);
timer = null;
},wait)
}
}
}
运行
function print(){
console.log('hello word');
}
//防抖
window.onscroll = anti(print,1000)
//节流
window.onscroll = throttle(print,1000)
递归实现深拷贝
let obj = {
name: '张三',
age: 18,
sex: '男',
child: {
name: '李四',
age: 30,
sex: '女',
child: {
name: '王五',
age: 200
}
}
}
// 深拷贝 递归算法实现对象的深拷贝
function deepClone(obj) {
let newObj = {}
for (let key in obj) {
// 判断 值是否是对象
if (obj[key] instanceof Object) {
newObj[key] = deepClone(obj[key])
} else {
newObj[key] = obj[key]
}
}
return newObj;
}
let res = deepClone(obj)
console.log(res);
// res.child.name = 'hello world';
// console.log(obj);
res.child.child.name = 'hello world 123';
console.log(obj);