1. 防抖
//原理 定时器或延时器
var content = document.getElementById("content");
var num = 1;
function count(){
content.innerHTML = num++;
}
content.onmousemove = count;
let times;
content.onmousemove = function (){
clearTimeout(times);
let obj = times;
times = setTimeout(()=>{
times = null;
},1000)
console.log(obj);
if(!obj){
content.innerHTML = num++;
}
};
2. 节流
1)
//时间戳
var content = document.getElementById("content");
var num = 1;
var timeNew = 0;
content.onmousemove = function(){
var timeOld = Date.now();
if(timeOld-timeNew>1000){
timeNew = timeOld;
content.innerHTML = num++;
}
}
2)
// 延时器
var content = document.getElementById("content");
var num = 1;
var time;
content.onmousemove = function(){
if(!time){
time = setTimeout(()=>{
time = null;
content.innerHTML = num++;
},1000)
}
}
数组扁平化
// 数组扁平化
var arr = [1, 2, 3, [4, 3, [2, 7], 2], 5, [5, 9, 10], 7];
// 最简单的方式(递归)
function func(user){
for(var i=0;i<user.length;i++){
if(Array.isArray(user[i])==false){
// arr.push(user[i]);
}else{
func(user[i]);
}
}
}
func(arr)
console.log(arr);
深拷贝递归
使用递归深拷贝
function deepClone(obj){
var objs = Array.isArray(obj)?[]:{};
if(obj&&typeof obj==="object"){
for(key in obj){
if(obj.hasOwnProperty(key)){
if(obj[key]&&typeof obj[key]==="object"){
objs[key] = deepClone(obj[key]);
}else{
objs[key] = obj[key];
}
}
}
}
return objs;
}