常用js工具函数整理(日期格式化,数组去重等)

日常项目开发中,会有一些重复使用的数据处理函数,于是就抽离出来封装在组件的工具类中。

1、判断是否是对象
/**
 * @param {Object} obj 对象
 */
export const isObj = (obj) => {
    // return Object.prototype.toString.call(obj) === '[Object Object]'
    return Object.prototype.toString.call(obj).slice(8, -1) === 'Object'
}

 

2、判断是否是数组
/**
 * @param {Array} arr 数组
 */
export const isArray = arr => {
    // return Object.prototype.toString.call(a) === '[object Array]'
    // return Object.prototype.toString.call(arr).slice(8, -1) === 'Array'
    return Array.isArray(arr)
}

其他如Function、Date、String等类型都可以通过 Object.prototype.toString() 来判断。

 

3、数组合并
/**
 * 数组合并(只支持一维数组)
 * @param {Array} arrOne
 * @param {Array} arrTwo
 */
export const arrConcat = (arrOne, arrTwo) => {
  return arrOne.concat(arrTwo.filter(v => !arrOne.includes(v))) // 含去重
}
​
export const arrConcat = (arrOne, arrTwo) => {
  return [...arrOne, ...arrTwo]
}

 

4、数组去重
  • 普通数组

    /**
     * @description 普通数组去重
     * @param {Array} arr 数组
     */
    export const arrDeduplication = arr => {
        // return [...new Set(arr)]
        return Array.from(new Set(arr))
    }
    ​
    // new Set(arr) 接受一个数组参数并生成一个set结构的数据类型。Set类似于数组,但它的成员是唯一的且是Array Iterator,所以可以利用这个特性来去重。
    // Array.from()方法将一个类数组对象或可迭代对象转换成一个新的浅拷贝的数组实例。

     

  • 数组对象

    /**
      * @description 数组对象去重方法一
      * @param {Array} arr 数组
      */
    export const arrDeduplication = arr => {
        const result = []
        arr.forEach(item => {
            !result.some(v => JSON.stringify(v) === JSON.stringify(item)) && result.push(item)
        })
        return result
    } 
    /** * @description 方法二 */ export const arrDeduplication = arr => { let obj = {} return arr.reduce((cur, next) => { obj[next.id] ? '' : obj[next.id] = true && cur.push(next) return cur }, []) }

    使用:

    const arr = [
        { name: '小明', id: 1 }, 
        { name: '小红', id: 2 }, 
        { name: '小李', id: 3 }, 
        { name: '小明', id: 1 }, 
        { name: '小张', id: 4 }, 
        { name: '小王', id: 5 }
    ]
    console.log(arrDeduplication(arr))
    ​
    // 打印结果 
    [
        { name: '小明', id: 1 },
        { name: '小红', id: 2 },
        { name: '小李', id: 3 },
        { name: '小张', id: 4 },
        { name: '小王', id: 5 }
     ]

     

5、判断数组(普通数组&数组对象)中是否包含值
/**
 * @description 数组中是否包含某值(普通数组)
 * @param {Array} arr 数组
 * @param {} value 值(支持String, Number, Boolean)
 */
export const isInclude = (arr, value) => {
  return arr.includes(value)
  // return arr.indexOf(value) !== -1 如果存在索引不等于-1
  // return arr.findIndex(item => item === value) !== -1 同上
  // return !arr.find(item => item === value) 如果数组中无值返回undefined
}
/** * @description 数组对象中是否包含某值 * @param {Array} arr 数组 */ export const isInclude = (arr, value) => { return arr.some(v => JSON.stringify(v) === JSON.stringify(value)) }

 

6、日期格式化
/**
  * @description 日期格式化,只需传入时间戳或者时间格式的字符串及要转换的时间格式
  * @param {Number} timestamp 时间戳或者时间格式的字符串
  * @param {String} format 时间格式,默认YYYY-MM-DD hh:mm:ss
  * @return {string} str 例如YYYY-MM-DD hh:mm:ss
  */
export const dateFmt = (timeStamp = Date.now(), format = 'YYYY-MM-DD hh:mm:ss') => {
    let date = new Date(timeStamp)
    let formatNumber = (n) => n < 10 ? ('0' + n) : n
    let str = format
        .replace('YYYY', date.getFullYear())
        .replace('MM', formatNumber(date.getMonth() + 1))
        .replace('DD', formatNumber(date.getDate()))
        .replace('hh', formatNumber(date.getHours()))
        .replace('mm', formatNumber(date.getMinutes()))
        .replace('ss', formatNumber(date.getSeconds()))
    return str
}
​
// 使用
dateFmt() // 默认返回当前时间,格式为 YYYY-MM-DD hh:mm:ss "2020-09-23 14:42:54"
dateFmt('2020-09-23', 'YYYY/MM/DD') // 2020/09/23
dateFmt(1600843532000) // 2020-09-23 14:45:32

还可以通过插件moment.js来格式化,不过现在已经不维护了

import moment from 'moment'/**
  * @description 传入时间戳(或者时间格式的数据),转换指定的时间格式
  * @param {Number} value 时间数据
  * @param {String} fmt 时间格式 例如 YYYY-MM-DD hh:mm:ss,默认为YYYY-MM-DD
  */
export const dateFmt = (value, fmt) => {
    if(value) {
        return moment(value).format(fmt || 'YYYY-MM-DD')
    } else {
        return ''
    }
}

 

7、安全的获取数组对应下标数据

这个方法我一般用在element-ui的日期范围选择器el-date-picker获取日期

/**
 * @param { Array } arr
 * @param { int } index
 */
export const arrGet = (arr, index) => {
    if( arr & Array.isArray(arr)) {
        return arr[index]
    } else {
        return undefined
    }
}

 

8、截取指定长度的字符串
/**
 * @description 截断字符
 * @type {{func: truncate.func}}
 */
export const truncate = (value, length) => {
    if(!value) return value
    if(value.length <= length) return value
    return value.slice(0, length) + '...'
}

 

9、设置 localStorage 本地存储和 cookie
/**
  * @description 设置本地localStorage存储(sessionStorage同理)
  * @name {String} 数据对象的key属性
  */
export function setStorage(key, data) {
  let storage = window.localStorage
  storage.setItem(key, JSON.stringify(data))
}
​
export function getStorage(key) {
  let storage = window.localStorage
  return JSON.parse(storage.getItem(key))
}
​
export const localStorageRemove = (key) => {
  localStorage.removeItem(key)
}

cookie操作方法:

/**
 * @description cookie操作方法
 * @param {String} key 属性
 * @param {*} value 值
 * @param String expiresTime 过期时间
 */
export const cookieUtils = {
    // 添加
    setCookie: (key, value, expiresTime) => {
        const d = new Date()
        d.setTime(d.getTime() + expiresTime)
        document.cookie = `${key}=${value}; expires=${d.toUTCString()}`
    },
    // 获取
    getCookie: key => {
        const name = `${key}=`
        const ca = document.cookie.split(';')
        for (let i = 0; i < ca.length; i++) {
            let c = ca[i]
            while(c.charAt(0) === '') c = c.substring(1)
            if(c.indexOf(name) !== -1) return c.substring(name.length, c.length)
        }
        return ''
    },
    // 删除
    clearCookie: key => {
        cookieUtils.setCookie(key, '', -1)
        // document.cookie = `${encodeURIComponent(key)}=;expires=${new Date()}`
    }
}

 

10、递归进行深拷贝
export const deepCopy = (obj) => {
    let result = Array.isArray(obj) ? [] : {}
    for (let key in obj) {
        if (obj.hasOwnProperty(key)) {
            if(typeof obj[key] === 'object' && obj[key] !== null) {
                result[key] = deepCopy(obj[key])
            } else {
                result[key] = obj[key]
            }
        }
    }
    return result;
}

 

11、邮箱校验
export const isEmail = (email) => {
    return /^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/.test(email)
}

 

12、手机号校验
export const isPhone = (phone) => {
    return /^1[0-9]{10}$/.test(phone)
}

 

13、身份证号校验
export const isIDCard = (card) => {
    return /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(card)
}

 

14、数字保留两位小数,并填入千分符
export const numberFmt = number => {
    if(!(number && number !== 0)) return '-';
    const integer = number
        .toFixed(2)
        .toString()
        .split('.');
    integer[0] = integer[0].replace(new RegExp('(\\d)(?=(\\d{3})+$)', 'ig'), '$1,');
    return integer.join('.');
}

 

15、小数转百分比
export const toPercentage = value => {
    if(isNaN(parseFloat(value))) {
        return value
    } else {
        return `${Math.round(parseFloat(value) * 10000 ) / 100}%`
    }
}

 

16、计算百分比
/**
 * @param val 数值
 * @param total 总数
 * @returns {string|number}
 */
export const getPercentage = (val, total) => {
    if(!val || !total) {
        return 0
    }
    return Math.round((val / total) * 10e3) / 100.0;
}

 

17、获取url参数
function getParamsString() {
    const url = document.location.toString()
    const arrUrl = url.split('?')
    if(arrUrl.length > 1) {
        const para = arrUrl[1]
        return decodeURIComponent(para)
    }
    return ''
}
​
const getUrlParams = key => {
    const str = getParamsString()
    const paramsList = str.split('&')
    const params = {}
    paramsList.forEach(e => {
        const arr = e.split('=')
        params[arr[0]] = arr[1] || ''
    })
    if(key) {
        return params[key] || ''
    }
    return params
}
​
export default getUrlParams

 

 

posted @ 2020-09-23 15:21  sugar_coffee  阅读(493)  评论(0编辑  收藏  举报