5个常见的前端功能你会写嘛

60 阅读1分钟

防抖

 //  1. 防抖
    function debounce(fn,time){
        let timer
        return function (...args){
            if(timer){
                clearTimeout(timer)
            }
            timer=setTimeout(()=>{
                fn.apply(this,args)
            },time)
        }
    }
    //测试
    function rask(){
    console.log('run task')
    }
    const debounceTask=debounce(task,1000)
    Window.addEventListener('scroll',debounceTask)
    

节流

 // 2.节流
    function throttle(fn,delay){
        let last=0 //上次触发事件
        return function (...args){
            const now=Date.now()
            if(now-last>delay){
                last=now
                fn.apply(this,args)
            }
        }
    }
    //测试
    function task(){
     console.log('run task')
    }
    const throttleTask=throttle(task,1000)
    Window.addEventListener('scroll',throttleTask)

深拷贝

//深拷贝
    // JSON方法
    //不支持值问undefined,函数和循环引用的情况
    const cloneObj=JSON.parse(JSON.stringify(obj))

数组排序

 //冒泡排序
    function Todo(arr){
        let len=arr.length
        for(let i = 0; i <len-1; i++) {
        //从第一个元素开始比较相邻的两个元素前者大就换位置
        for(let j = 0; j <len-1-i; j++) {
        if(arr[j]>arr[j+1]){
            let num=arr[j]
            arr[j]=arr[j+1]
            arr[j+1]=num
        }
    }
        }
        return arr
    }

数组去重

 // 数组去重
    // 1.set去重
    const newArr=[...new Set(arr)]
    //1.1
    const newArr=Array.from(new.Set(arr))

    //2.indexof
    const Array=arr.from((item,index)=>{
        arr.indexOf(item)===index
    })