JS功能函数

94 阅读2分钟

防抖节流

  document.querySelector('.btn1').addEventListener('click', debounce(fn, 2000))  
  document.querySelector('.btn2').addEventListener('click', throttle(fn1, 2000))   
 // 防抖函数   
 // 多次触发只发生一次(最后一次),在触发间隔前多次点击会清除然后重新间隔记时   
 function debounce(fn, second) {      
  let timer = null      
  return function () {     
   // console.log(this);   //同下的this          
  clearTimeout(timer)     
  timer = setTimeout(() => {     
       console.log(this);      
       fn.call(this, arguments);     //这里箭头函数的this为匿名函数的this,而dom事件函数的this指向绑定对象        
    }, second)  
   }  
 }  
  function fn() {  
     console.log('我是防抖函数,我在规定时间内无论点击多少次都只触发最后一次');  
  }  


  // 节流函数
  // 就是在规定时间内只是触发一次(第一次),当触发后,只有等待完成后改变阀门才可以再次触发 
     function throttle(fn, second) {   
     let flag = true      
     return function () {        
      if (!flag) {          
       return          
      }         
     flag = false        
    setTimeout(() => {       
      console.log(this);      
       fn.call(this.arguments)         
       flag = true         
      }, second)       
    } 
   }  
  function fn1() {    
    console.log('我是节流函数,我在第一次点击后在完成前无论点击多少次都只执行第一次');  
  }

深浅拷贝

 //深拷贝  
 function copy(obj) {    
    const fn = obj instanceof Array ? [] : {}     
    for (const [k, v] of Object.entries(obj)) {       
        fn[k] = typeof v === 'object' ? copy(v) : v 
     }      
    return fn  
  }   
 const fn = copy(par)

//浅拷贝
assign赋值
for循环赋值

数组去重

   const arr = [1, 2, 1, 4, 5, 6, 23, 1]  
  //  ES6数组去重    
function dum(a) {   
     const aa = Array.from(new Set([...a]))   //set里面的参数必须是数组,若是伪数组则解构转换  
      return aa   
 }   
 const newaa = dum(arr)  
  console.log(newaa);   


 // for循环数组去重 
   let ret = []   
 for (let i of arr) { 
       if (!ret.includes(i)) {    
        ret.push(i)     
   }  
  }  
  console.log(ret);

数据扁平

 // 扁平化操作   
 const fl = [12, 233, 12, [1, 2, 3, [7,8]]]    
function flatten(arr) { 
      return arr.reduce((result, item) => {   
         return result.concat(Array.isArray(item) ? flatten(item) : item)    
    }, [])   
 }  
  const flatf1 = flatten(fl)  
  console.log(fl);  
  console.log(flatf1);



const fl = [{
   children:{
    id:12000,
    label:'adf'
   }
   id:12000000,
   label:'qqere'
},{
 id:12530000,
 label:'fggg'}]    
  flatten(data: any) {    return data.reduce((result: any, item: any) => {      let obj = {        id: item.id,        label: item.label      };      return result.concat(        obj,        "children" in item ? this.flatten(item["children"]) : ""      );    }, []);  }







类数组转为数组

    const li = document.querySelectorAll('li')    console.log(li);

    // Array.from将伪数组转换为数组   
       const lis = Array.from(li)    
       console.log(lis);  

  // [].slice.apply将伪数组转换为数组  
    const lis2 = [].slice.apply(li)  //原数组不发生改变,返回操作后的新数组   
     console.log(lis2);   

    // 解构将伪数组转换为数组   
    const lis3 = [...li] 
     console.log(lis3);