Home > Web Front-end > JS Tutorial > body text

[Compilation and sharing] 11 practical tools and methods that must be learned in JS

青灯夜游
Release: 2022-10-12 19:24:42
forward
1363 people have browsed it

本篇文章给大家整理分享JavaScript 必须学会的11 个工具方法(避免重复造轮子),希望对大家有所帮助!

[Compilation and sharing] 11 practical tools and methods that must be learned in JS

前俩天也是更新了俩篇 JavaScript 的文章,当时由于时间问题,所以就是想到哪里写到哪里,因为对于技术文章只有三五句,几分钟就阅读完,属实无趣,这次趁着周六日有时间好好整理下,尽可量多写一些,下面有具体实现,还有详细注释

计算距离下次生日还有多少天

注意这里借助 moment 实现

    getBirthdayFun(){
       // 首先要获取到今年的生日
      let birthdayTime = moment().format('YYYY-') + '12-19'
      // 通过时间戳  去判断当前的时间戳是否大于今年生日的时间戳 
      if (moment().unix() >= moment(birthdayTime).unix()) {
        // 如果大于的话,那么就在今年的生日上再添加一年,已达到获取下次生日的时间
        birthdayTime = moment(birthdayTime).add(1, 'y').format('YYYY-MM-DD')
      }
      // 这个直接通过计算 (下次生日的时间戳 - 当前日期的时间戳) / (60 * 60 * 24) 最后求出来的就是 XX 天
      return parseInt(
        (moment(birthdayTime).unix() - moment().unix()) / (60 * 60 * 24)
      )
    }
Copy after login

回到顶部

    // 这里我把 vue3 的案例拿过来
    const bindTop = () => {
       // 方法一 这样可以实现,但是效果不太行
       window.scrollTo(0, 0)
       document.documentElement.scrollTop = 0;
        
      // 方法二 通过计时器去滚动 视觉上会丝滑一些,没有太大的卡顿效果
      const timeTop = setInterval(() => {
        // 去控制他的滑行距离
        document.documentElement.scrollTop = scrollTopH.value -= 50
        // 当滑到顶部的时候记得清除计时器(*) 重点
        if (scrollTopH.value <= 0) {
          clearInterval(timeTop)
        }
      }, 10)
    }
Copy after login

复制文本

    const copyText = (text) => {
        // clipboardData 在页面上将需要的东西复制到剪贴板上
        const clipboardData = window.clipboardData
        if (clipboardData) {
          clipboardData.clearData()
          clipboardData.setData('Text', text)
          return true
        } else if (document.execCommand) {  // 注意 document.execCommand 已弃用 但是有些浏览器依旧支持 用的时候记得看兼容情况
          // 通过创建 dom 元素,去把要复制的内容拿到 
          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()
          // 拷贝当前内容到剪贴板
          document.execCommand('copy')
          // 删除 el 节点
          document.body.removeChild(el)
          return true
        }
        return false
      }
      copyText('hello!') // ctrl + v = copyText  | true
Copy after login

防抖/节流

简单介绍

  • 防抖:指定时间内 频繁触发一个事件,以最后一次触发为准
  • 节流:指定时间内 频繁触发一个事件,只会触发一次

应用场景有很多比如:

防抖是: input搜索,用户在不断输入内容的时候,用防抖来减少请求的次数并且节约请求资源

节流:场景普遍就是按钮点击,一秒点击 10 下会发起 10 次请求,节流以后 1 秒点再多次,都只会触发一次

下面我们来实现

    // 防抖
    // fn 需要防抖的函数,delay 为定时器时间
    function debounce(fn,delay){
        let timer =  null  // 用于保存定时器
        return function () { 
            // 如果timer存在 就清除定时器,重新计时
            if(timer){
                clearTimeout(timeout);
            }
            //设置定时器,规定时间后执行真实要执行的函数
            timeout = setTimeout(() => {
               fn.apply(this);
            }, delay);
        }
    }
    
    // 节流
    function throttle(fn) {
      let timer = null; // 首先设定一个变量,没有执行定时器时,默认为 null
      return function () {
        if (timer) return; // 当定时器没有执行的时候timer永远是false,后面无需执行
        timer = setTimeout(() => {
          fn.apply(this, arguments);
           // 最后在setTimeout执行完毕后再把标记设置为true(关键)
           // 表示可以执行下一次循环了。
          timer = null;
        }, 1000);
      };
    }
Copy after login

过滤特殊字符

    function filterCharacter(str){
        // 首先设置一个模式
        let pattern = new RegExp("[`~!@#$^&*()=:”“'。,、?|{}':;'%,\\[\\].<>/?~!@#¥……&*()&;—|{ }【】‘;]")
        let resultStr = "";
        for (let i = 0; i < str.length; i++) {
            // 主要通过 replace ,pattern 规则 去把字符替换成空 最后拼接在 resultStr
            resultStr = resultStr + str.substr(i, 1).replace(pattern, &#39;&#39;);
        }
        // 当循环结束的时候返回最后结果 resultStr
        return resultStr;
    }
    
    // 示例
    filterCharacter(&#39;gyaskjdhy12316789#$%^&!@#1=123,./[&#39;) // 结果:gyaskjdhy123167891123
Copy after login

常用正则判断

    // 校验2-9位文字 不符合为 false  符合为 true
    const validateName = (name) => {
      const reg = /^[\u4e00-\u9fa5]{2,9}$/;
      return reg.test(name);
    };

    // 校验手机号
    const validatePhoneNum = (mobile) => {
      const reg = /^1[3,4,5,6,7,8,9]\d{9}$/;
      return reg.test(mobile);
    };

    // 校验6到18位大小写字母数字下划线组成的密码
    const validatePassword = (password) => {
      const reg = /^[a-zA-Z0-9_]{6,18}$/;
      return reg.test(password);
    };
Copy after login

初始化数组

    // fill()方法 是 es6新增的一个方法 使用指定的元素填充数组,其实就是用默认内容初始化数组
    const arrList = Array(6).fill()
    console.log(arrList)  // 此处打印的是 ['','','','','','']
Copy after login

将 RGB 转换为十六进制

    function getColorFun(r,g,b) {
       return '#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)
    }
    
    getColorFun(178,232,55) // 这里输出的是 #b2e837
Copy after login

检测是否是一个函数

    // 检测是否是一个函数  其实写法以后直接 isFunction 就好了,避免重复写判断
    const isFunction = (obj) => {
        return typeof obj === "function" && typeof obj.nodeType !== "number" && typeof obj.item !== "function";
    };
Copy after login

检测是否为一个安全数组

  // 检测是否为一个安全数组,若不是返回空数组  这里借助isArray 方法
  const safeArray = (array) => {
    return Array.isArray(array) ? array : []
  }
Copy after login

检测对象是否为一个安全对象

    // 首先要去判断 当前对象是否为有效对象 
    const isVaildObject = (obj) => {
        return typeof obj === 'object' && !Array.isArray(obj) && Object.keys(obj).length
    }
    // 这里直接用上面的函数 如果有效就返回本身,无效就返回空对象
    const safeObject = obj => isVaildObject(obj) ? obj : {}
Copy after login

最后

上面案例有些代码都是在我单独的 v3 项目里面,如果有需要可以关注我,然后找我要资料,或者需要面试题什么的也都可以找我,都有哈,上面文章如果有不清楚的地方,麻烦指出,希望对大家都能有一定程度的帮助,谢谢支持~

(学习视频分享:web前端开发编程基础视频

The above is the detailed content of [Compilation and sharing] 11 practical tools and methods that must be learned in JS. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:juejin.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!