你可能会用到的JS工具函数

开发 开发工具
我们今天聊聊你可能会用到的JS工具函数,你能用到几个?

[[403909]]

Vue3在script标签中引入

  1. const oDiv = document.createElement('div'); 
  2.     const oScript = document.createElement('script'); 
  3.     oDiv.setAttribute('id''app'); 
  4.     oScript.type = 'text/javascript'
  5.     oScript.src = "https://unpkg.com/vue@next"
  6.     document.body.appendChild(oDiv); 
  7.     document.body.appendChild(oScript); 
  8.  
  9.  
  10.     window.onload = function () { 
  11.       const { createApp,ref } = Vue; 
  12.       const App = { 
  13.         template: ` 
  14.             <div>{{msg}}</div> 
  15.             <p>{{count}}</p> 
  16.             `, 
  17.         data(){ 
  18.               return { 
  19.                 msg:'maomin' 
  20.               } 
  21.         }, 
  22.         setup(){ 
  23.           let count = ref(0); 
  24.  
  25.           return { 
  26.             count 
  27.           } 
  28.         } 
  29.     } 
  30.      createApp(App).mount('#app'); 
  31.     } 

递归寻找操作(已删除指定项为例)

  1. // 递归寻找 
  2.     recursion(data, id) { 
  3.       let result; 
  4.       if (!data) { 
  5.         return
  6.       } 
  7.       for (let i = 0; i < data.length; i++) { 
  8.         let item = data[i]; 
  9.         if (item.breakerId === id) { 
  10.           result = item; 
  11.           data.splice(i, 1); 
  12.           break; 
  13.         } else if (item.childrenBranch && item.childrenBranch.length > 0) { 
  14.           result = this.recursion(item.childrenBranch, id); 
  15.           if (result) { 
  16.             return result; 
  17.           } 
  18.         } 
  19.       } 
  20.  
  21.       return result; 
  22.     }, 

递归数组,将数组为空设为undefined

  1. function useTree(data) { 
  2.        for (let index = 0; index < data.length; index++) { 
  3.          const element = data[index]; 
  4.          if (element.childrenBranch.length < 1) { 
  5.            element.childrenBranch = undefined; 
  6.          } else { 
  7.            useTree(element.childrenBranch); 
  8.          } 
  9.        } 
  10.        return data; 
  11.      } 

数组对象中相同属性值的个数

  1. group(arr) { 
  2.       var obj = {}; 
  3.       if (Array.isArray(arr)) { 
  4.         for (var i = 0; i < arr.length; ++i) { 
  5.           var isNew = arr[i].isNew; 
  6.           if (isNew in obj) obj[isNew].push(arr[i]); 
  7.           else obj[isNew] = [arr[i]]; 
  8.         } 
  9.       } 
  10.       return obj; 
  11.     }, 
  12.     max(obj) { 
  13.       var ret = 0; 
  14.       if (obj && typeof obj === "object") { 
  15.         for (var key in obj) { 
  16.           var length = obj[key].length; 
  17.           if (length > ret) ret = length; 
  18.         } 
  19.       } 
  20.       return ret; 
  21.     }, 
  22. var data = [ 
  23.     { 
  24.      addr: "1"
  25.      isNew: false
  26.     }, 
  27.     { 
  28.      addr: "2"
  29.      isNew: false
  30.     } 
  31. max(group(data) // 2 

检测版本是vue3

  1. import { h } from 'vue'
  2. const isVue3 = typeof h === 'function'
  3. console.log(isVue3) 

检测数据对象中是否有空对象

  1. let arr = [{},{name:'1'}] 
  2. const arr = this.bannerList.filter(item => 
  3.        item == null || item == '' || JSON.stringify(item) == '{}' 
  4. ); 
  5.  console.log(arr.length > 0 ? '不通过' : '通过'

深拷贝

  1.  /* @param {*} obj 
  2.  * @param {Array<Object>} cache 
  3.  * @return {*} 
  4.  */ 
  5. function deepCopy (obj, cache = []) { 
  6.   // just return if obj is immutable value 
  7.   if (obj === null || typeof obj !== 'object') { 
  8.     return obj 
  9.   } 
  10.  
  11.   // if obj is hit, it is in circular structure 
  12.   const hit = find(cache, c => c.original === obj) 
  13.   if (hit) { 
  14.     return hit.copy 
  15.   } 
  16.  
  17.   const copy = Array.isArray(obj) ? [] : {} 
  18.   // put the copy into cache at first 
  19.   // because we want to refer it in recursive deepCopy 
  20.   cache.push({ 
  21.     original: obj, 
  22.     copy 
  23.   }) 
  24.  
  25.   Object.keys(obj).forEach(key => { 
  26.     copy[key] = deepCopy(obj[key], cache) 
  27.   }) 
  28.  
  29.   return copy 
  30.  
  31. const objs = { 
  32.     name:'maomin'
  33.     age:'17' 
  34.  
  35. console.log(deepCopy(objs)); 

h5文字转语音

  1. speech(txt){ 
  2.     var synth = null
  3.     var msg = null
  4.     synth = window.speechSynthesis; 
  5.     msg = new SpeechSynthesisUtterance(); 
  6.     msg.text = txt; 
  7.     msg.lang = "zh-CN"
  8.     synth.speak(msg); 
  9.     if(window.speechSynthesis.speaking){ 
  10.       console.log("音效有效"); 
  11.      } else { 
  12.      console.log("音效失效"); 
  13.      } 
  14.  } 

模糊搜索

  1. recursion(data, name) { 
  2.             let result; 
  3.             if (!data) { 
  4.                 return
  5.             } 
  6.             for (var i = 0; i < data.length; i++) { 
  7.                 let item = data[i]; 
  8.                 if (item.name.toLowerCase().indexOf(name) > -1) { 
  9.                     result = item; 
  10.                     break; 
  11.                 } else if (item.children && item.children.length > 0) { 
  12.                     result = this.recursion(item.children, name); 
  13.                     if (result) { 
  14.                         return result; 
  15.                     } 
  16.                 } 
  17.             } 
  18.             return result; 
  19.         }, 
  20.         onSearch(v) { 
  21.             if (v) { 
  22.                 if (!this.recursion(this.subtable, v)) { 
  23.                     this.$message({ 
  24.                         type: 'error'
  25.                         message: '搜索不到'
  26.                     }); 
  27.                 } else { 
  28.                     this.tableData = [this.recursion(this.subtable, v)]; 
  29.                 } 
  30.             } 
  31.         }, 

input 数字类型

  1.   <el-input 
  2.                    v-model.number="form.redVal" 
  3.                    type="number" 
  4.                    @keydown.native="channelInputLimit" 
  5.                    placeholder="请输入阈值设定" 
  6.                    maxlength="8" 
  7. ></el-input> 
  8.  
  9.    channelInputLimit(e) { 
  10.        let key = e.key
  11.        // 不允许输入‘e‘和‘.‘ 
  12.        if (key === 'e' || key === '.') { 
  13.            e.returnValue = false
  14.            return false
  15.        } 
  16.        return true
  17.    }, 

排序(交换位置)

  1. const list = [1,2,3,4,5,6]; 
  2.     function useChangeSort (arr,oldIndex,newIndex){ 
  3.         const targetRow = arr.splice(oldIndex, 1)[0]; 
  4.         const targetRow1 = arr.splice(newIndex, 1)[0]; 
  5.         arr.splice(newIndex, 0, targetRow); 
  6.         arr.splice(oldIndex, 0, targetRow1); 
  7.         return arr 
  8.     } 
  9.     console.log(useChangeSort(list,5,0)); // [6, 2, 3, 4, 5, 1] 

格式化时间

  1. /** 
  2.  * Parse the time to string 
  3.  * @param {(Object|string|number)} time 
  4.  * @param {string} cFormat 
  5.  * @returns {string | null
  6.  */ 
  7. export function parseTime(time, cFormat) { 
  8.     if (arguments.length === 0 || !time) { 
  9.         return null
  10.     } 
  11.     const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  12.     let date
  13.     if (typeof time === 'object') { 
  14.         date = time
  15.     } else { 
  16.         if (typeof time === 'string') { 
  17.             if (/^[0-9]+$/.test(time)) { 
  18.                 // support "1548221490638" 
  19.                 time = parseInt(time); 
  20.             } else { 
  21.                 // support safari 
  22.                 // https://stackoverflow.com/questions/4310953/invalid-date-in-safari 
  23.                 time = time.replace(new RegExp(/-/gm), '/'); 
  24.             } 
  25.         } 
  26.  
  27.         if (typeof time === 'number' && time.toString().length === 10) { 
  28.             time = time * 1000; 
  29.         } 
  30.         date = new Date(time); 
  31.     } 
  32.     const formatObj = { 
  33.         y: date.getFullYear(), 
  34.         m: date.getMonth() + 1, 
  35.         d: date.getDate(), 
  36.         h: date.getHours(), 
  37.         i: date.getMinutes(), 
  38.         s: date.getSeconds(), 
  39.         a: date.getDay() 
  40.     }; 
  41.     const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => { 
  42.         const value = formatObj[key]; 
  43.         // Note: getDay() returns 0 on Sunday 
  44.         if (key === 'a') { 
  45.             return ['日''一''二''三''四''五''六'][value]; 
  46.         } 
  47.         return value.toString().padStart(2, '0'); 
  48.     }); 
  49.     return time_str; 

本文转载自微信公众号「前端历劫之路」,可以通过以下二维码关注。转载本文请联系前端历劫之路公众号。

 

责任编辑:武晓燕 来源: 前端历劫之路
相关推荐

2011-08-31 16:01:33

2021-08-06 07:55:55

黑客工具网站临时手机号

2015-04-08 09:54:41

OpenStack资源私有云部署

2020-07-06 07:48:16

MySQL细节SQL

2020-12-08 05:56:51

JS工具函数

2018-07-10 11:05:18

开发者技能命令

2018-07-10 10:45:00

规范Commit项目

2020-10-08 18:14:15

码农Git命令

2016-03-16 11:20:47

2022-04-24 10:51:57

Python漏洞

2010-06-21 10:34:03

职场信号被炒

2020-10-13 08:40:01

CSS多行多列布局

2017-03-23 16:03:01

2017-11-21 10:15:00

2014-02-18 10:59:52

nftablesLinux 3.13

2017-11-23 11:56:00

2020-03-09 10:10:02

AI 数据人工智能

2020-09-01 14:17:03

WindowsDefender微软

2019-03-22 08:00:01

Git命令GitHub

2021-12-29 22:29:10

JavaScript前端数组
点赞
收藏

51CTO技术栈公众号