JavaScript 实用工具函数

1. 数组操作

生成指定范围随机整数

// [min, max]
const randomNum = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;

2. 数组操作

  1. 打乱数组
    const arrScrambling = (arr) => {
        for (let i = 0; i < arr.length; i++) {
          const randomIndex = Math.round(Math.random() * (arr.length - 1 - i)) + i;
          [arr[i], arr[randomIndex]] = [arr[randomIndex], arr[i]];
        }
        return arr;
    }
    
  2. 随机获取数组中的数
    const sample = arr => arr[Math.floor(Math.random() * arr.length)];
    

3. 字符串操作

  1. 随机生成字符串:使用0123456789ABCDEF随机生成形如xxxxxxxx-xxxx-xxxx-xxxxxxxxxxxxxxxxx的字符串
    function creatGUID(){
    	let arr = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F']
    	let res = []
    	for(let i = 0;i<32;i++){
    		let num = Math.floor(Math.random()*16);
    		res.push(arr[num])
    	}
    	let result = res.slice(0,8).join('')+'-'+res.slice(8,12).join('')+'-'+res.slice(12,16).join('')+'-'+res.slice(16).join('')
    	return result
    }
    console.log(creatGUID());
    
  2. 字符串首字母大写
    const fistLetterUpper = (str) => {
        return str.charAt(0).toUpperCase() + str.slice(1);
    };
    
  3. 驼峰命名转换成短横线命名
    export const getKebabCase = (str) => {
        return str.replace(/[A-Z]/g, (item) => '-' + item.toLowerCase())
    }
    
  4. 短横线命名转换成驼峰命名
    export const getCamelCase = (str) => {
        return str.replace( /-([a-z])/g, (i, item) => item.toUpperCase())
    }
    

4. 存储操作

  1. 存储loalStorage
    const loalStorageSet = (key, value) => {
        if (!key) return;
        if (typeof value !== 'string') {
            value = JSON.stringify(value);
        }
        window.localStorage.setItem(key, value);
    };
    
  2. 获取localStorage
    const loalStorageGet = (key) => {
        if (!key) return;
        return window.localStorage.getItem(key);
    };
    
  3. 删除localStorage
    const loalStorageRemove = (key) => {
        if (!key) return;
        window.localStorage.removeItem(key);
    };
    
  4. 存储sessionStorage
    const sessionStorageSet = (key, value) => {
       if (!key) return;
        if (typeof value !== 'string') {
          value = JSON.stringify(value);
        }
        window.sessionStorage.setItem(key, value)
    };
    
  5. 获取sessionStorage
    const sessionStorageGet = (key) => {
       if (!key) return;
        return window.sessionStorage.getItem(key)
    };
    
  6. 删除sessionStorage
    const sessionStorageRemove = (key) => {
       if (!key) return;
        window.sessionStorage.removeItem(key)
    };
    
  7. 设置cookie
    Data对象
    const setCookie = (key, value, expire) => {
        const d = new Date();
        d.setDate(d.getDate() + expire);
        document.cookie = `${key}=${value};expires=${d.toUTCString()}`
    };
    
  8. 读取cookie
    const getCookie = (key) => {
    	// 解码 decodeURI()
        const cookieStr = decodeURI(document.cookie);
        const arr = cookieStr.split(';');
        let cookieValue = '';
        for (let i = 0; i < arr.length; i++) {
           const temp = arr[i].split('=');
           if (temp[0] === key) {
               cookieValue = temp[1];
               break
           }
        }
        return cookieValue
    };
    
  9. 删除cookie
    const delCookie = (key) => {
    	// 编码 encodeURIComponent()
        document.cookie = `${encodeURIComponent(key)}=;expires=${new Date()}`
    };
    

5. URL操作

location对象

  1. 获取URL参数列表
    const GetRequest = () => {
        let url = location.search;
        const paramsStr = /.+\?(.+)$/.exec(url)[1]; // 将 ? 后面的字符串取出来
        const paramsArr = paramsStr.split('&'); // 将字符串以 & 分割后存到数组中
        let paramsObj = {};
        // 将 params 存到对象中
        paramsArr.forEach(param => {
          if (/=/.test(param)) { // 处理有 value 的参数
            let [key, val] = param.split('='); // 分割 key 和 value
            val = decodeURIComponent(val); // 解码
            val = /^\d+$/.test(val) ? parseFloat(val) : val; // 判断是否转为数字
            if (paramsObj.hasOwnProperty(key)) { // 如果对象有 key,则添加一个值
              paramsObj[key] = [].concat(paramsObj[key], val);
            } else { // 如果对象没有这个 key,创建 key 并设置值
              paramsObj[key] = val;
            }
          } else { // 处理没有 value 的参数
            paramsObj[param] = true;
          }
        })
        return paramsObj;
    };
    
  2. 键值对拼接成URL参数
    const params2Url = (obj) => {
         let params = []
         for (let key in obj) {
           params.push(`${key}=${obj[key]}`);
         }
         return encodeURIComponent(params.join('&'))
    }
    

6. 浏览器操作

  1. 滚动到页面顶部
    const scrollToTop = () => {
      const height = document.documentElement.scrollTop || document.body.scrollTop;
      if (height > 0) {
        window.requestAnimationFrame(scrollToTop);
        window.scrollTo(0, height - height / 8);
      }
    }
    
  2. 滚动到页面底部
    const scrollToBottom = () => {
      window.scrollTo(0, document.documentElement.clientHeight);  
    }
    
  3. 滚动到指定元素区域
    const smoothScroll = (element) => {
        document.querySelector(element).scrollIntoView({
            behavior: 'smooth'
        });
    };
    
  4. 获取可视窗口高度
    const getClientHeight = () => {
        let clientHeight = 0;
        if (document.body.clientHeight && document.documentElement.clientHeight) {
            clientHeight = (document.body.clientHeight < document.documentElement.clientHeight) ? document.body.clientHeight : document.documentElement.clientHeight;
        }
        else {
            clientHeight = (document.body.clientHeight > document.documentElement.clientHeight) ? document.body.clientHeight : document.documentElement.clientHeight;
        }
        return clientHeight;
    }
    
  5. 获取可视窗口宽度
    export const getPageViewWidth = () => {
        return (document.compatMode == "BackCompat" ? document.body : document.documentElement).clientWidth;
    }
    

7. 时间操作

  1. 当前时间
    const nowTime = () => {
        const now = new Date();
        const year = now.getFullYear();
        const month = now.getMonth();
        const date = now.getDate() >= 10 ? now.getDate() : ('0' + now.getDate());
        const hour = now.getHours() >= 10 ? now.getHours() : ('0' + now.getHours());
        const miu = now.getMinutes() >= 10 ? now.getMinutes() : ('0' + now.getMinutes());
        const sec = now.getSeconds() >= 10 ? now.getSeconds() : ('0' + now.getSeconds());
        return +year + "年" + (month + 1) + "月" + date + "日 " + hour + ":" + miu + ":" + sec;
    }
    
  2. 格式化时间
    export const dateFormater = (formater, time) => {
        let date = time ? new Date(time) : new Date(),
            Y = date.getFullYear() + '',
            M = date.getMonth() + 1,
            D = date.getDate(),
            H = date.getHours(),
            m = date.getMinutes(),
            s = date.getSeconds();
        return formater.replace(/YYYY|yyyy/g, Y)
            .replace(/YY|yy/g, Y.substr(2, 2))
            .replace(/MM/g,(M<10 ? '0' : '') + M)
            .replace(/DD/g,(D<10 ? '0' : '') + D)
            .replace(/HH|hh/g,(H<10 ? '0' : '') + H)
            .replace(/mm/g,(m<10 ? '0' : '') + m)
            .replace(/ss/g,(s<10 ? '0' : '') + s)
    }
    // dateFormater('YYYY-MM-DD HH:mm:ss')
    // dateFormater('YYYYMMDDHHmmss')
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值