求数组对象的最大值
let a
const arr = [{name:"nanlan",num:20},{name:"xiaojuju",num:21},{name:"yunju",num:22}]
const max = Math.max(...arr.map(item=>item.num)); // 22
求连续出现次数最多的字符
let str = 'aabbbbccc';
let arr = str.match(/(\w)\1*/g); // ['aa','bbb','ccc']
let maxLen = Math.max(...arr.map(item=>item.length)); // 3
const result = arr.reduce((pre, curr) => {
if (curr.length === maxLen) {
pre[curr] = curr.length;
}
return pre;
}, {}); // { c: 3},reduce 的第二个参数是初始值的意思
数组对象去重
const fn = arr =>{
const res = [];
const map = arr.reduce((cur,next)=> (cur[next.id] = next),{})
return map;
}
const arr = [{id: 1}, {id:2, pId: 1}, {id: 3, pId: 2}, {id: 4}, {id:3, pId: 2}, {id: 5, pId: 4}]
console.log(fn(arr));
数组变成对象
Object.values(obj)对象变成数组
防抖与节流
//场景: input
function debounce(fn){
let timeout = null;
return function(){
clearTimeout(timeout); // 每当执行的时候,就把上次的函数清除掉
timeout = setTimeout(function(){
fn.apply(this,arguments);
},500)
}
}
// 场景:resize、scroll、click、hover
function throttle(fn){
let canRun = true;
return function(){
if(!canRun)return;
canRun = false;
setTimeout((){
fn.apply(this,arguments);
// 最后在setTimout执行完毕后再吧标记设置为true,表示可以进入下一次循环了
canRun = ture;
},500)
}
}
function sayHi(){
console.log("Hi")
}
doucment.getElementById("app").addListener("input",debounce(hi))
网友评论