工具函数(不知道你们能不能用得上)

简介: 工具函数(不知道你们能不能用得上)

获取URL中指定的查询参数值


在理解这个函数之前,我们需要介绍一些几个api


  • encodeURIComponent这个api对于大多数字符都是转义的,对于下面这部分不会转义。


不转义的字符:
    A-Z a-z 0-9 - _ . ! ~ * ' ( )


  • encodeURI他会转义所有字符,将其转为%编码的格式。但是下面这类字符不会被转义。这个也就是通常我们复制url到文本编辑器时所转义的格式了。


类型 包含
保留字符 ;,/?:@&=+$
非转义的字符 字母 数字 -_.!~*'()
数字符号 #


  • decodeURIComponent这个api的解码能力更加强大,因为他可以解码encodeURI, encodeURIComponent编码的url。


  • decodeURI这个api的只能解码由encodeURI编码的url了。


下面给出一个实例,可以自己举例子测试一下。


const url = "http://localhost:8080?name=张----_昊&age=30"
    const encode = encodeURIComponent(url) 
    console.log("编码 encodeURIComponent", encode) // http%3A%2F%2Flocalhost%3A8080%3Fname%3D%E5%BC%A0----_%E6%98%8A%26age%3D30
    const encode2 = encodeURI(url)
    console.log("编码 encodeURI", encode2) // http://localhost:8080?name=%E5%BC%A0----_%E6%98%8A&age=30
    const decode = decodeURIComponent(encode)
    console.log("解码", decode) // http://localhost:8080?name=张----_昊&age=30
    const decode2 = decodeURI(encode)
    console.log("解码", decode2) // http%3A%2F%2Flocalhost%3A8080%3Fname%3D张----_昊%26age%3D30


工具函数


const getURLParam = function (name, targetUrl) {
      var reg = new RegExp('[?&]' + name + '=([^&]+)')
      targetUrl = targetUrl || window.location.search
      var newurl = decodeURIComponent(targetUrl)
      return newurl.match(reg) ? RegExp.$1 : null
    }
    const url = "http://localhost:8080?name=张昊&age=30"
    console.log(getURLParam("name", url)) // 张昊


按照json对象中的key升序排列


jsonSortId = function (json) {
      let arr = []
      for (var key in json) {
        arr.push(key)
      }
      // 默认是升序排列,将key升序,然后在取值,返回。
      arr.sort()
      let newjson = {}
      for (var i in arr) {
        var key = arr[i]
        newjson[key] = json[key]
      }
      return newjson
    }


将json对象转为url参数


parseParams = (data) => {
      try {
        var tempArr = []
        for (var i in data) {
          // 将一些非ascii或者uri的保留字转为%编码
          var key = encodeURIComponent(i)
          var value = encodeURIComponent(data[i])
          tempArr.push(key + '=' + value)
        }
        // 在进行拼接
        var urlParamsStr = tempArr.join('&')
        return urlParamsStr
      } catch (err) {
        return ''
      }
    }


剪切板


const clipboard = (text) => {
      return new Promise((resolve, reject) => {
        // 创建隐藏的 Textarea 标签,并将文本放入其中
        let textarea = document.createElement('textarea')
        textarea.style.position = 'absolute'
        textarea.style.top = '0'
        textarea.style.left = '0'
        textarea.style.border = 'none'
        textarea.style.margin = '0'
        textarea.style.padding = '0'
        textarea.style.opacity = '0'
        textarea.value = text
        document.body.appendChild(textarea)
        // 复制 Textarea 标签的文本
        textarea.select()
        document.execCommand('copy')
        // 移除 Textarea 标签
        document.body.removeChild(textarea)
        resolve()
      })
    }


测试这个工具函数


<!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Document</title>
    </head>
    <body>
      <p id="p">这里是需要复制的文本</p>
      <div id="div">点击复制</div>
      <script>
        var clipboard = (text) => {
          return new Promise((resolve, reject) => {
            // 创建隐藏的 Textarea 标签,并将文本放入其中
            let textarea = document.createElement('textarea')
            textarea.style.position = 'absolute'
            textarea.style.top = '0'
            textarea.style.left = '0'
            textarea.style.border = 'none'
            textarea.style.margin = '0'
            textarea.style.padding = '0'
            textarea.style.opacity = '0'
            textarea.value = text
            document.body.appendChild(textarea)
            // 复制 Textarea 标签的文本
            textarea.select()
            document.execCommand('copy')
            // 移除 Textarea 标签
            document.body.removeChild(textarea)
            resolve()
          })
        }
        const p = document.getElementById("p")
        const div = document.getElementById("div")
        div.onclick = function() {
          clipboard(p.innerText).then(() => {
            console.log("复制成功")
          }).catch(err => {
            console.log("复制失败")
          })
        }
      </script>
    </body>
    </html>


网络异常,图片无法展示
|


对于一些数据类型的判断


const funProto = Function.prototype
    const objProto = Object.prototype
    const getPrototypeOf = Object.getPrototypeOf
    const objToString = objProto.toString
    const hasOwnProperty = objProto.hasOwnProperty
    const funToString = funProto.toString
    // 检查给定的值是否是 dom 元素
    export function isElement(value) {
      return !!(value && value.nodeType === 1)
    }
    // 检查给定的值是否是 null
    export function isNull(value) {
      return value === null
    }
    // 检查给定的值是否是 undefined
    export function isUndefined(value) {
      return value === void 0
    }
    // 检查给定的值是否是 NaN
    // 这和原生的 isNaN 函数不一样,如果变量是 undefined,原生的 isNaN 函数也会返回 true
    export function isNaN(value) {
      return window.isNaN(value) && value !== value
    }
    // 检查给定的值是否是数值
    export function isNumber(value) {
      return objToString.call(value) === '[object Number]' && !isNaN(value)
    }
    // 检查给定的值是否是字符串
    export function isString(value) {
      return objToString.call(value) === '[object String]'
    }
    // 检查给定的值是否是布尔值
    export function isBoolean(value) {
      return (
        value === true ||
        value === false ||
        objToString.call(value) === '[object Boolean]'
      )
    }
    // 检查给定的值是否是正则表达式
    export function isRegExp(value) {
      return objToString.call(value) === '[object RegExp]'
    }
    // 检查给定的值是否是日期对象
    export function isDate(value) {
      return objToString.call(value) === '[object Date]'
    }
    // 检查给定的值是否是函数
    export function isFunction(value) {
      return (
        objToString.call(value) === '[object Function]' ||
        typeof value === 'function'
      )
    }
    // 检查给定的值是否是数组
    export function isArray(value) {
      return objToString.call(value) === '[object Array]'
    }
    // 检查给定的值是否是对象
    export function isObject(value) {
      return !!value && typeof value === 'object'
    }
    // 检查给定的值是否是纯对象,纯对象是指通过 {} 或 new Object() 声明的对象
    export function isPlainObject(value) {
      if (!value || objToString.call(value) !== '[object Object]') {
        return false
      }
      var prototype = getPrototypeOf(value)
      if (prototype === null) {
        return true
      }
      var constructor =
        hasOwnProperty.call(prototype, 'constructor') && prototype.constructor
      return (
        typeof constructor === 'function' &&
        funToString.call(constructor) === funToString.call(Object)
      )
    }
    //
    export default {
      element: isElement,
      null: isNull,
      undefined: isUndefined,
      nan: isNaN,
      number: isNumber,
      string: isString,
      boolean: isBoolean,
      regexp: isRegExp,
      date: isDate,
      function: isFunction,
      array: isArray,
      object: isObject,
      plainObject: isPlainObject,
    }


相关文章
|
2月前
|
存储 小程序 数据库
零基础开发小程序第五课-修改数据
零基础开发小程序第五课-修改数据
|
3月前
|
JavaScript Java Python
Web自动化三种等待方式,一篇文章教会你
Web自动化三种等待方式,一篇文章教会你
67 1
|
9月前
|
存储 JSON Kubernetes
证书管理工具 cfssl 浅尝
证书管理工具 cfssl 浅尝
175 0
|
5月前
|
存储 开发者
彻底搞懂微信小游戏制作工具中的函数
彻底搞懂微信小游戏制作工具中的函数
53 0
|
10月前
|
JavaScript 前端开发 测试技术
6款程序员实用工具,老少皆宜,你一定用得上!
6款程序员实用工具,老少皆宜,你一定用得上!
|
11月前
|
存储 小程序 数据库
零基础开发小程序第五课-修改数据(一)
零基础开发小程序第五课-修改数据(一)
|
11月前
|
小程序
零基础开发小程序第五课-修改数据(二)
零基础开发小程序第五课-修改数据(二)
|
12月前
|
API Windows
VBA 有用的小段代码收藏(日积月累)
VBA 有用的小段代码收藏(日积月累)
92 0
|
uml 开发者 Windows
推荐5款冷门小工具,看一看有没有你喜欢的?
每个人的电脑中都会安装很多软件,可能还保留着很多不为人知的冷门软件。不过虽然冷门,但绝不意味着低能,相反很多冷门软件的功能十分出色。闲话少说,接下来我就给大家推荐5款冷门小工具,看一看有没有你喜欢的。
147 0
推荐5款冷门小工具,看一看有没有你喜欢的?
|
传感器
时隔这么长时间,我把常用的功能整理好了,再来感受VueUse工具库的优雅吧~
时隔这么长时间,我把常用的功能整理好了,再来感受VueUse工具库的优雅吧~
时隔这么长时间,我把常用的功能整理好了,再来感受VueUse工具库的优雅吧~