e判断函数

判断数据类型

  1. function getType(source) {
  2. Object.prototype.toString.call(source).slice(8, -1).toLowerCase()
  3. }

非空判断

  1. function isEmpty (v) {
  2. const type = Object.prototype.toString.call(v).slice(8, -1).toLowerCase()
  3. if (type === 'string' || type === 'array') {
  4. return !v.length
  5. }
  6. else if (type === 'object') {
  7. return !Object.keys(v).length
  8. } else if (type === 'number') {
  9. return !v
  10. } else {
  11. return !v
  12. }
  13. }

数据处理

kebabCase - CamelCase - PascalCase

card-item => cardItem

  1. function kebab2Camel (str) {
  2. /**
  3. * $ - 匹配值
  4. * $1 - 第一个捕获值
  5. */
  6. return str.replace(/-([a-z])/g, ($, $1) => {
  7. return $1.toUpperCase()
  8. })
  9. }

card-item => CardItem

  1. function kebab2Pascal (str) {
  2. const Camel = str.replace(/-([a-z])/g, ($, $1) => {
  3. return $1.toUpperCase()
  4. })
  5. return Camel ? Camel[0].toUpperCase() + Camel.slice(1) : ''
  6. }

对象 => formData

  1. function obj2FormData (obj) {
  2. const formData = new FormData()
  3. for (const key in obj) {
  4. formData.append(key, obj[key])
  5. }
  6. return formData
  7. }

对象 => URL

  1. function obj2Params (obj) {
  2. let arr = []
  3. for (const key in obj) {
  4. if (Object.hasOwnProperty.call(obj, key)) {
  5. arr.push(`${key}=${obj[key]}`)
  6. }
  7. }
  8. return arr.length ? '?' + arr.join('&') : ''
  9. }

日期格式化

时间戳格式化

  1. function dateFormat(t, format) {
  2. let date = t ? new Date(t) : new Date(),
  3. Y = date.getFullYear() + '',
  4. M = date.getMonth() + 1,
  5. D = date.getDate(),
  6. H = date.getHours(),
  7. m = date.getMinutes(),
  8. s = date.getSeconds()
  9. if (date.toString() === 'Invalid Date') return '-/-'
  10. return format
  11. .replace(/YYYY|yyyy/g, Y)
  12. .replace(/YY|yy/g, Y.substr(2, 2))
  13. .replace(/MM/g, (M < 10 ? '0' : '') + M)
  14. .replace(/DD|dd/g, (D < 10 ? '0' : '') + D)
  15. .replace(/HH|hh/g, (H < 10 ? '0' : '') + H)
  16. .replace(/mm/g, (m < 10 ? '0' : '') + m)
  17. .replace(/ss/g, (s < 10 ? '0' : '') + s)
  18. }

时间戳格式化(消息)

  1. function handleDate(date) {
  2. const val = new Date(date).getTime()
  3. const now = Date.now()
  4. const diff = now - val
  5. if(diff < 0 ) return '未知'
  6. const second = 1000
  7. const min = 60 * second
  8. const hour = 60 * min
  9. const day = 24 * hour
  10. const month = 30 * day
  11. const year = 12 * month
  12. const fl = Math.floor
  13. const base = {
  14. second,
  15. min,
  16. hour,
  17. day,
  18. month,
  19. year
  20. }
  21. const end = {}
  22. for (const key in base) {
  23. end[key] = fl(diff / base[key])
  24. }
  25. console.log(end);
  26. if (end.year > 0) {
  27. return `${end.year}年前`
  28. } else if (end.month > 0) {
  29. return `${end.month}月前`
  30. } else if (end.day) {
  31. return `${end.day}天前`
  32. } else if (end.hour) {
  33. return `${end.hour}小时前`
  34. } else if (end.min) {
  35. return `${end.min}分钟前`
  36. } else if (end.second) {
  37. return `${end.second}秒前`
  38. }else {
  39. return '刚刚'
  40. }
  41. }

时间格式化(转 1小时30分)

  1. function showDate(v, isMs = true) {
  2. const unit = isMs ? 1000 : 1
  3. const base = {
  4. second: unit,
  5. min: 60 * unit,
  6. hour: 60 * 60 * unit,
  7. day: 24 * 60 * 60 * unit
  8. }
  9. const fl = Math.floor
  10. const s = fl((v % base.min) / base.second)
  11. const m = fl((v % base.hour) / base.min)
  12. const h = fl((v % base.day) / base.hour)
  13. const d = fl(v / base.day)
  14. console.log(s, m, h, d)
  15. let str = ''
  16. d && (str += d + '天')
  17. h && (str += h + '小时')
  18. m && (str += m + '分')
  19. s && (str += s + '秒')
  20. return str
  21. }

异步封装

query 是一个 promise 对象。可以搭配 promise.all 实现异步函数循环

  1. function handlePromise (promise) {
  2. return new Promise((resolve, reject) => {
  3. promise.then(res => resolve(res)).catch(err => reject(err))
  4. })
  5. }e
  1. let arr = []
  2. api.forEach((v)=>{
  3. const promise = ajax(...)
  4. arr.push(promise)
  5. })
  6. const res = Promise.all(arr)

杂谈

封装函数 - 直接返回和闭包返回的区别

  1. let cl = {
  2. add: function (a, b) {
  3. console.log(a, b);
  4. return a + b + 2;
  5. },
  6. };
  7. function test1() {
  8. const { add } = cl;
  9. return add;
  10. }
  11. function test2() {
  12. const { add } = cl;
  13. return function (query) {
  14. return add(query);
  15. };
  16. }
  17. const add1 = test1;
  18. const add2 = test2;
  19. console.log(add1()(1, 2));
  20. console.log(add2()(1, 2));

待归档

1汉字2字符

  1. function validateTextLength (value, length = 12) {
  2. let cnReg = /([\u4e00-\u9fa5]|[\u3000-\u303F]|[\uFF00-\uFF60])/g;
  3. let mat = value.match(cnReg);
  4. // let length = 0;
  5. if (mat) {
  6. return (length = mat.length + (value.length - mat.length) * 0.5);
  7. } else {
  8. return (length = value.length * 0.5);
  9. }
  10. }

深拷贝

递归版

  1. function deepClone (source) {
  2. if (typeof source !== 'object' || source == null) return source
  3. let res
  4. if (Array.isArray(source)) {
  5. res = []
  6. } else {
  7. res = {}
  8. }
  9. for (const key in source) {
  10. if (Object.hasOwnProperty.call(source, key)) {
  11. res[key] = deepClone(source[key])
  12. }
  13. }
  14. return res
  15. }

获得hash ID

  1. function _hashId(length = 32){
  2. return Array.from({length}, () => Math.floor(Math.random() * 36).toString(36)).join('')
  3. }

Regexp

筛选字符串中数组

'1,2,3,4,[7,8,9],4,5,7,[111,22,44]' =>["1", "2", "3", "4", "[7,8,9]", "4", "5", "7", "[111,22,44]"]

  1. const str = '1,2,3,4,[7,8,9],4,5,7,[111,22,44,a]';
  2. const reg = /(\[.*?\])|,/g;
  3. const arr = str.split(reg).filter(Boolean);
  4. console.log(arr);

匹配标点

  1. // 匹配标点 - 存在兼容性问题
  2. /p{P}/u
  3. /[\u0021|\u0022|\u0027|\u002C|\u002E|\u003A|\u003B|\u003F|\u0060|\u3002|\uff1f|\uff01|\uff0c|\u3001|\uff1b|\uff1a|\u201c|\u201d|\u2018|\u2019|\uff08|\uff09|\u300a|\u300b|\u3008|\u3009|\u3010|\u3011|\u300e|\u300f|\u300c|\u300d|\ufe43|\ufe44|\u3014|\u3015|\u2026|\u2014|\uff5e|\ufe4f|\uffe5]+/u
  1. \u0021 => !
  2. \u0022 => "
  3. \u0027 => '
  4. \u002C => ,
  5. \u002E => .
  6. \u003A => :
  7. \u003B => ;
  8. \u003F => ?
  9. \u0060 => `
  10. \u3002 => 。
  11. \uff1f => ?
  12. \uff01 => !
  13. \uff0c => ,
  14. \u3001 => 、
  15. \uff1b => ;
  16. \uff1a => :
  17. \u201c => “
  18. \u201d => ”
  19. \u2018 => ‘
  20. \u2019 => '
  21. \uff08 => (
  22. \uff09 => )
  23. \u300a => 《
  24. \u300b => 》
  25. \u3008 => 〈
  26. \u3009 => 〉
  27. \u3010 => 【
  28. \u3011 => 】
  29. \u300e => 『
  30. \u300f => 』
  31. \u300c => 「
  32. \u300d => 」
  33. \ufe43 => ﹃
  34. \ufe44 => ﹄
  35. \u3014 => 〔
  36. \u3015 => 〕
  37. \u2026 => …
  38. \u2014 => —
  39. \uff5e => ~
  40. \ufe4f => ﹏
  41. \uffe5 => ¥

https://unicode-table.com/en/blocks/basic-latin/