JS小知识,分享工作中常用的八个封装函数,让你事半功倍

开发 后端
工作中经常用到的 8 个Javascript方法,记住并收藏这些方法,避免重新发明轮子。

一、回到顶部

当页面很长时,如果用户想回到页面顶部,必须滚动滚动键几次才能回到顶部。如果页面右下角有“返回顶部”按钮,用户可以点击返回顶部。对于用户来说,这是一个很好的用户体验。

// 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)
  }

二、将文本复制到剪贴板

构建网站时一个非常普遍的需求是能够通过单击按钮将文本复制到剪贴板。以下这段代码是一个很通用的代码,适合大多数浏览器。

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
    }

三、防抖/节流

在前端开发的过程中,我们会遇到很多按钮被频繁点击,然后触发多个事件,但是我们又不想触发事件太频繁。这里有两种常见的解决方案来防止 Debouncing 和 Throttling。

基本介绍

防抖:在指定时间内频繁触发事件,以最后一次触发为准。

节流:一个事件在指定时间内被频繁触发,并且只会被触发一次,以第一次为准。

应用场景

防抖: 输入搜索,当用户不断输入内容时,使用防抖来减少请求次数,节省请求资源。

节流:场景一般是按钮点击。一秒内点击 10 次将发起 10 个请求。节流后,1秒内点击多次,只会触发一次。

// 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);
      };
    }

四、初始化数组

fill() :这是 ES6 中的一个新方法。用指定的元素填充数组,实际上就是用默认的内容初始化数组。

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

五、检查它是否是一个函数

检测是否是函数 其实写完后直接写isFunction就好了,这样可以避免重复写判断。

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

六、检查它是否是一个安全数组

检查它是否是一个安全数组,如果不是,用 isArray 方法在这里返回一个空数组。

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中使用正则表达式过滤特殊字符,检查所有输入字段是否包含特殊字符。

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

结束

今天的分享就到这里,这8个方法你学会了吗,我强烈建议大家收藏起来,别再造轮子了。希望今天的分享能够帮助到你,感谢你的阅读。

责任编辑:姜华 来源: 今日头条
相关推荐

2020-05-13 21:09:10

JavaScript前端技术

2024-01-11 09:21:13

JavaScript工具JSON

2020-09-16 11:10:33

Linux命令文件

2019-08-07 16:50:38

SQLjoingroup

2022-12-13 08:23:25

CSS前端渐变

2023-11-22 18:04:50

快捷键• macOS

2024-01-31 08:47:05

JavaScript工具函数JS

2017-11-21 15:34:15

Linux 开发开源

2023-11-26 17:47:00

数据分析

2023-02-22 19:15:35

AI工具机器人

2021-08-28 11:47:52

json解析

2021-10-27 17:57:35

设计模式场景

2021-09-23 15:13:02

Spring依赖Java

2022-10-10 09:00:35

ReactJSX组件

2011-06-03 17:50:58

2020-12-16 08:33:57

JS函数效率

2023-12-19 13:30:00

JavaScrip原生API函数

2018-11-19 15:06:23

Python算法

2023-02-23 19:24:53

人工智能工具

2010-08-25 11:14:05

云安全数据安全网络安全
点赞
收藏

51CTO技术栈公众号