关于javascript:常用js工具函数整理日期格式化数组去重等

1次阅读

共计 6009 个字符,预计需要花费 16 分钟才能阅读完成。

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

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、Data、String 等类型都能够通过 Object.prototype.toString() 来判断。

3、数组合并
/**
 * @description 数组合并(只反对一维数组)* @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 数组对象去重办法二
  * @param {Array} arr 数组
  */
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 截断字符
 * @param {int} length 长度
 */
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 const setStorage = (key, data) => {
    let storage = window.localStorage
    storage.setItem(key, JSON.stringify(data))
}

export const 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 numberFormatter = 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
正文完
 0