utils.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. // 工具类
  2. // 随机获取数组中的num个元素并返回新数组
  3. export function getArrayItems(arr, num) {
  4. const newArr = []
  5. for (let i = 0; i <= num - 1; i++) {
  6. // 生成数组长度范围内的随机数
  7. const index = Math.floor(Math.random() * arr.length)
  8. newArr[i] = arr.splice(index, 1)[0]
  9. }
  10. return newArr
  11. }
  12. // 23000 =》 2.3万
  13. export function handleVisited(visited) {
  14. // console.log(visited);
  15. if (visited >= 10000) {
  16. var s = Math.floor(visited / 10000)
  17. var s2 = Math.floor(visited % 10000 / 1000)
  18. visited = s + '.' + s2 + '万'
  19. }
  20. return visited
  21. }
  22. // 时间的转换
  23. export function getDate(pretime) {
  24. const minute = 1000 * 60
  25. const hour = minute * 60
  26. const day = hour * 24
  27. const month = day * 30
  28. // 将时间转化为时间戳
  29. pretime = pretime.replace(/\-/g, '/')
  30. const time = new Date(pretime).getTime()
  31. // 获取当前时间戳
  32. const now = new Date().getTime()
  33. const subTime = now - time
  34. const monthC = subTime / month
  35. const weekC = subTime / (7 * day)
  36. const dayC = subTime / day
  37. const hourC = subTime / hour
  38. const minC = subTime / minute
  39. if (monthC >= 1) {
  40. return parseInt(monthC) + '个月前'
  41. } else if (weekC >= 1) {
  42. return parseInt(weekC) + '周前'
  43. } else if (dayC >= 1) {
  44. return parseInt(dayC) + '天前'
  45. } else if (hourC >= 1) {
  46. return parseInt(hourC) + '小时前'
  47. } else if (minC >= 1) {
  48. return parseInt(minC) + '分钟前'
  49. } else {
  50. return '刚刚'
  51. }
  52. }
  53. // 获取唯一的id
  54. export function getUUid() {
  55. var s = []
  56. var hexDigits = '0123456789abcdef'
  57. for (var i = 0; i < 36; i++) {
  58. s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
  59. }
  60. s[14] = '4' // bits 12-15 of the time_hi_and_version field to 0010
  61. s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1) // bits 6-7 of the clock_seq_hi_and_reserved to 01
  62. s[8] = s[13] = s[18] = s[23] = '-'
  63. var uuid = s.join('')
  64. return uuid
  65. }
  66. // 时间格式化
  67. export function formatDate(date, fmt) {
  68. if (/(y+)/.test(fmt)) {
  69. fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  70. }
  71. const o = {
  72. 'M+': date.getMonth() + 1,
  73. 'd+': date.getDate(),
  74. 'h+': date.getHours(),
  75. 'm+': date.getMinutes(),
  76. 's+': date.getSeconds()
  77. }
  78. for (const k in o) {
  79. if (new RegExp(`(${k})`).test(fmt)) {
  80. const str = o[k] + ''
  81. fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str))
  82. }
  83. }
  84. return fmt
  85. }
  86. function padLeftZero(str) {
  87. return ('00' + str).substr(str.length)
  88. }