• 常见的一些小函数集合


    1. 提取所有连续重复的字符 例如12323454545666,提取[ ‘23’, ‘45’, ‘6’ ]

    /**
     * 分析:
     * a) 写有一个字符重复的正则 /(.)\1/ ,\1表示重复 
     * b) 写n个有重复字符的正则 /(.+)\1+/
     * c) 提取所有连续的字符
     */
      const collectRepeatStr = (str) => {
        let repeatStrs = []
        const repeatRe = /(.+)\1+/g
        str.replace(repeatRe, ($0, $1) => {
          $1 && repeatStrs.push($1)
        })
        return repeatStrs
      }
      console.log(collectRepeatStr('12323454545666')) // ["23", "45", "6"]
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    2. 实现trim函数

    // 去除空格法,即将空格部分删除,保留非空格的部分
    const trim = (str) => {
       return str.replace(/^\s*|\s*$/g, '')    
     }
     // 提取非空格法,把非空格的部分提取出来,不管空格部分
     const trim = (str) => {
       return str.replace(/^\s*(.*?)\s*$/g, '$1')    
     }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    3. 数字千位分割

    /**
     * 分析: 
     * 从后往前,每三个数字前加一个逗号,开头不能加
     * a) 
     */
      '123456789'.replace(/(?!^)(?=(\d{3})+$)/g, ',') // 123,456,789
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    4. 手机号3-4-4分割

    let mobile = '18379836654' 
    let mobileReg = /(?=(\d{4})+$)/g 
    console.log(mobile.replace(mobileReg, '-')) // 183-7983-6654
    
    • 1
    • 2
    • 3

    5. 将字符串驼峰化 foo Bar => fooBar; foo-bar---- => fooBar; foo_bar__ => fooBar

    /**
     * 分析
     * a) 每个单词的前面都有0个或者多个- 空格 _ 如(Foo、--foo、__FOO、_BAR、Bar)
     * b) - 空格 _后面有可能不跟任何东西 如(__、--)
     */
      const camelCase = (string) => {
        // 注意(.)?这里的?是为了满足条件b
        const camelCaseRegex = /[-_\s]+(.)?/g
        return string.replace(camelCaseRegex, (match, char) => {
          return char ? char.toUpperCase() : ''
        })
      }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    6. 将字符串首字母转化为大写,剩下为小写 例如 hello world 转为为Hello World

      const capitalize = (string) => {
        const capitalizeRegex = /(?:^|\s+)\w/g
        return string.toLowerCase().replace(capitalizeRegex, (match) => match.toUpperCase())
      }
    
    • 1
    • 2
    • 3
    • 4

    7. 通过name获取url query参数

    /**
     * url query上的参数 name=章三 所处的位置可能是
     *  a) 紧跟着问号 ?name=章三&sex=boy
     *  b) 在最后的位置 ?sex=boy&name=章三
     *  c) 在 a 和 b 之间 ?sex=boy&name=章三&age=100
     * 
     * 即:
     * a) name前面只能是?或者&
     * b) value的值可以除了是&以为的任意东西
     * c) value后面只能是跟着&或者是结束位置
     */
      const getQueryByName = (name) => {
        const queryNameRegex = new RegExp(`[?&]${name}=([^&]*)(&|$)`)
        const queryNameMatch = window.location.search.match(queryNameRegex)
        // 一般都会通过decodeURIComponent解码处理
        return queryNameMatch ? decodeURIComponent(queryNameMatch[1]) : ''
      }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    8. 扁平数据结构转tree

    /**
      * 待转换格式:
    	let arr = [
    		{id: 1, name: '部门1', pid: 0},
    		{id: 2, name: '部门2', pid: 1},
    		{id: 3, name: '部门3', pid: 1},
    		{id: 4, name: '部门4', pid: 3},
    		{id: 5, name: '部门5', pid: 4},
    	]
      * 目标格式:
    	[
    	    { id: 1, name: 部门1, pid: 0, children: [
    			{ id: 2, name: 部门2, pid: 1, children: []},
    			{ id: 3, name: 部门3, pid: 1, children: [ // 结果 ,,, ] }
    	    ]}
    	]
    	
      * 思路:
      * 1. 递归方式: 主要是提供一个一个方法去查找子集。
      * 2. 非递归方式: 先将数据转为Map去存储,之后遍历的同事借助对象的引用,直接从Map中找对应的数据存储
     */
    	/**
    	 * 递归查找,获取children
    	 */
    	function getChildren (data, result, pid) {
    	  for (const item of data) {
    		if (item.pid === pid) {
    		  const newItem = {...item, children: []};
    		  result.push(newItem);
    		  getChildren(data, newItem.children, item.id);
    		}
    	  }
    	}
    	/**
    	* 转换方法
    	*/
    	function arrayToTree (data, pid) {
    	  const result = [];
    	  getChildren(data, result, pid)
    	  return result;
    	}
    	console.log(arrayToTree(arr, 0))
    	
    /** ---------------------------------------------- */
    
    	/**
    	 * 非递归方式
    	 */
    	function array2Tree(items) {
    	  const result = [];   // 存放结果集
    	  const itemMap = {};  // 
    	  for (const item of items) {
    		const id = item.id;
    		const pid = item.pid;
    		if (!itemMap[id]) {
    		  itemMap[id] = {
    			children: [],
    		  }
    		}
    		itemMap[id] = {
    		  ...item,
    		  children: itemMap[id]['children']
    		}
    		const treeItem =  itemMap[id]
    		if (pid === 0) {
    		  result.push(treeItem);
    		} else {
    		  if (!itemMap[pid]) {
    			itemMap[pid] = {
    			  children: [],
    			}
    		  }
    		  itemMap[pid].children.push(treeItem)
    		}
    	  }
    	  return result;
    	}
    	console.log(array2Tree(arr))
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78

    9. 实现文件下载

    downloadTask(params).then(res=> {
    	  // 1
    	  const fileName = res.headers['content-disposition'].split('=')[1];
    	  const _res = res.data;
    	  const blob = new Blob([_res]);
    	  const downloadElement = document.createElement('a');
    	  const href = window.URL.createObjectURL(blob); // 创建下载的链接
    	  downloadElement.href = href;
    	  downloadElement.download = decodeURI(fileName); // 下载后文件名
    	  document.body.appendChild(downloadElement);
    	  downloadElement.click(); // 点击下载
    	  document.body.removeChild(downloadElement); // 下载完成移除元素
    	  window.URL.revokeObjectURL(href); // 释放掉blob对象
    	  
    	  // 2
    	  var disposition = {}
    	  var headersContent = res.headers['content-disposition'].split(';')
    	  headersContent.forEach(item => {
    	    const itemArr = item.split('=')
    	    disposition[itemArr[0].trim()] = itemArr[1] ? itemArr[1] : ''
    	  })
    	  const blob = new Blob([JSON.stringify(res.data)])
    	  if (window.navigator.msSaveOrOpenBlob) {
    	  // 兼容IE10
    	    navigator.msSaveBlob(blob, disposition.fileName)
    	  } else {
    	  //  chrome/firefox
    	    const aTag = document.createElement('a')
    	    aTag.download = disposition.fileName
    	    aTag.href = URL.createObjectURL(blob)
    	    aTag.click()
    	    URL.revokeObjectURL(aTag.href)
    	  }
    	  });
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34

    10. 深拷贝

     // 方法1 Object.getOwnPropertyDescriptors() 方法用来获取一个对象的所有自身属性的描述符。返回所指定对象的所有自身属性的描述符,如果没有任何自身属性,则返回空对象。
    // 这样做的好处就是能够提前定义好最后返回的数据类型。
     function deepClone(obj) {
         let res = null;
         const reference = [Date, RegExp, Set, WeakSet, Map, WeakMap, Error];
         if (reference.includes(obj?.constructor)) {
             res = new obj.constructor(obj);
         } else if (Array.isArray(obj)) {
             res = [];
             obj.forEach((e, i) => {
                 res[i] = deepClone(e);
             });
         } else if (typeof obj === "Object" && obj !== null) {
             res = {};
             for (const key in obj) {
                 if (Object.hasOwnProperty.call(obj, key)) {
                     res[key] = deepClone(obj[key]);
                 }
             }
         } else {
             res = obj;
         }
         return res;
     }
     // 方法2: 用hash来存储已经加载过的对象,如果已经存在的对象,就直接返回。
     function deepClone(obj, hash = new WeakMap()) {
         if (hash.has(obj)) {
             return obj;
         }
         let res = null;
         const reference = [Date, RegExp, Set, WeakSet, Map, WeakMap, Error];
     
         if (reference.includes(obj?.constructor)) {
             res = new obj.constructor(obj);
         } else if (Array.isArray(obj)) {
             res = [];
             obj.forEach((e, i) => {
                 res[i] = deepClone(e);
             });
         } else if (typeof obj === "Object" && obj !== null) {
             res = {};
             for (const key in obj) {
                 if (Object.hasOwnProperty.call(obj, key)) {
                     res[key] = deepClone(obj[key]);
                 }
             }
         } else {
             res = obj;
         }
         hash.set(obj, res);
         return res;
     }
     // 方法3: iview 方案
     function deepCopy(data) {
         const t = typeOf(data);
         let o;
         if (t === 'array') {
             o = [];
         } else if ( t === 'object') {
             o = {};
         } else {
             return data;
         }
         if (t === 'array') {
             for (let i = 0; i < data.length; i++) {
                 o.push(deepCopy(data[i]));
             }
         } else if ( t === 'object') {
             for (let i in data) {
                 o[i] = deepCopy(data[i]);
             }
         }
         return o;
     }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74

    11. 生产随机字符

    function randomStr (len = 32) {
        const $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
        const maxPos = $chars.length;
        let str = '';
        for (let i = 0; i < len; i++) {
            str += $chars.charAt(Math.floor(Math.random() * maxPos));
        }
        return str;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    12.判断元素重复次数

    arrCheck(data, key) {
        const arr = JSON.parse(JSON.stringify(data))
        const obj = {}
        for (var i = 0; i < arr.length; i++) {
           var temp = arr[i][key]
           var count = 0
           for (var j = 0; j < arr.length; j++) {
              if (arr[j][key] === temp) {
    	          count++
    	          arr[j][key] = -1
              }
           }
           if (temp !== -1) {
              obj[temp] = count
           }
        }
        return obj
     }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    13. 将对象中的数据,按照key进行排序

    function objKeySort(arys) {
    	//先用Object内置类的keys方法获取要排序对象的属性名,再利用Array原型上的sort方法对获	取的属性名进行排序,newkey是一个数组
    	var newkey = Object.keys(arys).sort();
    	//console.log('newkey='+newkey);
    	var newObj = {}; //创建一个新的对象,用于存放排好序的键值对
    	for (var i = 0; i < newkey.length; i++) { //遍历newkey数组
    		newObj[newkey[i]] = arys[newkey[i]]; //向新创建的对象中按照排好的顺序依次增加键值对   
    	}
    	return newObj; //返回排好序的新对象
    }
    
    var objKey = {
    	analysis: ['0'],
    	vLevel: ['warn', 'error'],
    	app: ['app']
    }
    
    console.log(objKeySort(objKey))
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
  • 相关阅读:
    PCF8574/ PCF8574A/ PCF8574T I2C to parellal 8-bits I/O
    mac使用python递归删除文件夹下所有的.DS_Store文件
    无敌!我用【C语言】手搓出了一个体系完整的【员工管理系统】还能玩游戏听音乐?(超详细,附完整源码)
    ES6相关语法规范
    学习 Mybatis
    centos 通过yum安装nginx
    大型集团企业数据集成研究
    uniapp的实战总结大全
    git详细教程
    GB/T 7134-2008 浇筑型工业有机玻璃板材检测
  • 原文地址:https://blog.csdn.net/weixin_43972213/article/details/126581113