自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

JS小知識,分享工作中常用的八個封裝函數(shù),讓你事半功倍

開發(fā) 后端
工作中經(jīng)常用到的 8 個Javascript方法,記住并收藏這些方法,避免重新發(fā)明輪子。

一、回到頂部

當(dāng)頁面很長時,如果用戶想回到頁面頂部,必須滾動滾動鍵幾次才能回到頂部。如果頁面右下角有“返回頂部”按鈕,用戶可以點擊返回頂部。對于用戶來說,這是一個很好的用戶體驗。

// Method 1
  constbindTop1 = () => {
      window.scrollTo(0, 0)
      document.documentElement.scrollTop = 0;
  }
  
  
    // Method 2: Scrolling through the timer will be visually smoother, without much lag effect
    constbindTop2 = () => {
      const timeTop = setInterval(() => {
        document.documentElement.scrollTop = scrollTopH.value -= 50
        if (scrollTopH.value <= 0) {
          clearInterval(timeTop)
        }
      }, 10)
  }

二、將文本復(fù)制到剪貼板

構(gòu)建網(wǎng)站時一個非常普遍的需求是能夠通過單擊按鈕將文本復(fù)制到剪貼板。以下這段代碼是一個很通用的代碼,適合大多數(shù)瀏覽器。

const copyText = (text) => {
        const clipboardStr = window.clipboardStr
        if (clipboardStr) {
          clipboardStr.clearData()
          clipboardStr.setData('Text', text)
          return true
        } else if (document.execCommand) {  
          //Note: document, execCommand is deprecated but some browsers still support it. Remember to check the compatibility when using it
          // Get the content to be copied by creating a dom element
          const el = document.createElement('textarea')
          el.value = text
          el.setAttribute('readonly', '')
          el.style.position = 'absolute'
          el.style.left = '-9999px'
          document.body.appendChild(el)
          el.select()
          // Copy the current content to the clipboard
          document.execCommand('copy')
          // delete el node
          document.body.removeChild(el)
          return true
        }
        return false
    }

三、防抖/節(jié)流

在前端開發(fā)的過程中,我們會遇到很多按鈕被頻繁點擊,然后觸發(fā)多個事件,但是我們又不想觸發(fā)事件太頻繁。這里有兩種常見的解決方案來防止 Debouncing 和 Throttling。

基本介紹

防抖:在指定時間內(nèi)頻繁觸發(fā)事件,以最后一次觸發(fā)為準(zhǔn)。

節(jié)流:一個事件在指定時間內(nèi)被頻繁觸發(fā),并且只會被觸發(fā)一次,以第一次為準(zhǔn)。

應(yīng)用場景

防抖: 輸入搜索,當(dāng)用戶不斷輸入內(nèi)容時,使用防抖來減少請求次數(shù),節(jié)省請求資源。

節(jié)流:場景一般是按鈕點擊。一秒內(nèi)點擊 10 次將發(fā)起 10 個請求。節(jié)流后,1秒內(nèi)點擊多次,只會觸發(fā)一次。

// Debouncing
    // fn is the function that needs anti-shake, delay is the timer time
    function debounce(fn,delay){
        let timer = null;
        return function () { 
            //if the timer exists, clear the timer and restart the timer
            if(timer){
                clearTimeout(timeout);
            }
            //Set a timer and execute the actual function to be executed after a specified time
            timeout = setTimeout(() => {
               fn.apply(this);
            }, delay);
        }
    }
    
    // Throttling
    function throttle(fn) {
      let timer = null; // First set a variable, when the timer is not executed, the default is null
      return function () {
        if (timer) return; // When the timer is not executed, the timer is always false, and there is no need to execute it later
        timer = setTimeout(() => {
          fn.apply(this, arguments);
           // Finally, set the flag to true after setTimeout is executed
           // Indicates that the next cycle can be executed.
          timer = null;
        }, 1000);
      };
    }

四、初始化數(shù)組

fill() :這是 ES6 中的一個新方法。用指定的元素填充數(shù)組,實際上就是用默認(rèn)的內(nèi)容初始化數(shù)組。

const arrList = Array(6).fill()
   console.log(arrList)  // result:  ['','','','','','']

五、檢查它是否是一個函數(shù)

檢測是否是函數(shù) 其實寫完后直接寫isFunction就好了,這樣可以避免重復(fù)寫判斷。

const isFunction = (obj) => {
        return typeof obj === "function" &&
          typeof obj.nodeType !== "number" && 
          typeof obj.item !== "function";

六、檢查它是否是一個安全數(shù)組

檢查它是否是一個安全數(shù)組,如果不是,用 isArray 方法在這里返回一個空數(shù)組。

const safeArray = (array) => {
    return Array.isArray(array) ? array : []
}

七、檢查對象是否是安全對象

// Check whether the current object is a valid object.
    const isVaildObject = (obj) => {
        return typeof obj === 'object' && 
          !Array.isArray(obj) && Object.keys(obj).length
    }
    const safeObject = obj => isVaildObject(obj) ? obj : {}

八、過濾特殊字符

js中使用正則表達(dá)式過濾特殊字符,檢查所有輸入字段是否包含特殊字符。

function filterCharacter(str){
        let pattern = new RegExp("[`~!@#$^&*()=:”“'。,、?|{}':;'%,\\[\\].<>/?~!@#¥……&*()&;—|{ }【】‘;]")
        let resultStr = "";
        for (let i = 0; i < str.length; i++) {
            resultStr = resultStr + str.substr(i, 1).replace(pattern, '');
        }
        return resultStr;
    }
    
  
    filterCharacter('gyaskjdhy12316789#$%^&!@#1=123,./[') 
// result: gyaskjdhy123167891123

結(jié)束

今天的分享就到這里,這8個方法你學(xué)會了嗎,我強烈建議大家收藏起來,別再造輪子了。希望今天的分享能夠幫助到你,感謝你的閱讀。

責(zé)任編輯:姜華 來源: 今日頭條
相關(guān)推薦

2020-05-13 21:09:10

JavaScript前端技術(shù)

2024-01-11 09:21:13

JavaScript工具JSON

2019-08-07 16:50:38

SQLjoingroup

2020-09-16 11:10:33

Linux命令文件

2022-12-13 08:23:25

CSS前端漸變

2023-11-22 18:04:50

快捷鍵? macOS

2024-01-31 08:47:05

JavaScript工具函數(shù)JS

2021-08-28 11:47:52

json解析

2017-11-21 15:34:15

Linux 開發(fā)開源

2023-11-26 17:47:00

數(shù)據(jù)分析

2024-04-28 11:22:18

2021-10-27 17:57:35

設(shè)計模式場景

2023-02-22 19:15:35

AI工具機器人

2021-09-23 15:13:02

Spring依賴Java

2024-12-11 08:20:57

設(shè)計模式源碼

2022-10-10 09:00:35

ReactJSX組件

2020-12-16 08:33:57

JS函數(shù)效率

2023-12-19 13:30:00

JavaScrip原生API函數(shù)

2011-06-03 17:50:58

2025-04-23 08:20:00

Linux性能監(jiān)測命令
點贊
收藏

51CTO技術(shù)棧公眾號