tools.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. // 小数运算精度处理 4位小数运算后结果保留2位小数
  2. export const getOperationalPrecision = (num1, num2) => {
  3. const val = ((num1 * 10000) * (num2 * 10000) / 100000000).toFixed(2) || 0
  4. return val != 0 ? val : 0
  5. }
  6. export const forEach = (arr, fn) => {
  7. if (!arr.length || !fn) return
  8. let i = -1
  9. const len = arr.length
  10. while (++i < len) {
  11. const item = arr[i]
  12. fn(item, i, arr)
  13. }
  14. }
  15. /**
  16. * @param {Array} arr1
  17. * @param {Array} arr2
  18. * @description 得到两个数组的交集, 两个数组的元素为数值或字符串
  19. */
  20. export const getIntersection = (arr1, arr2) => {
  21. const len = Math.min(arr1.length, arr2.length)
  22. let i = -1
  23. const res = []
  24. while (++i < len) {
  25. const item = arr2[i]
  26. if (arr1.indexOf(item) > -1) res.push(item)
  27. }
  28. return res
  29. }
  30. /**
  31. * @param {Array} arr1
  32. * @param {Array} arr2
  33. * @description 得到两个数组的并集, 两个数组的元素为数值或字符串
  34. */
  35. export const getUnion = (arr1, arr2) => {
  36. return Array.from(new Set([...arr1, ...arr2]))
  37. }
  38. /**
  39. * @param {Array} target 目标数组
  40. * @param {Array} arr 需要查询的数组
  41. * @description 判断要查询的数组是否至少有一个元素包含在目标数组中
  42. */
  43. export const hasOneOf = (targetarr, arr) => {
  44. if (!targetarr) return true
  45. if (!arr) return true
  46. return targetarr.some(_ => arr.indexOf(_) > -1)
  47. }
  48. /**
  49. * @param {String|Number} value 要验证的字符串或数值
  50. * @param {*} validList 用来验证的列表
  51. */
  52. export function oneOf (value, validList) {
  53. for (let i = 0; i < validList.length; i++) {
  54. if (value === validList[i]) {
  55. return true
  56. }
  57. }
  58. return false
  59. }
  60. /**
  61. * @param {Number} timeStamp 判断时间戳格式是否是毫秒
  62. * @returns {Boolean}
  63. */
  64. const isMillisecond = timeStamp => {
  65. const timeStr = String(timeStamp)
  66. return timeStr.length > 10
  67. }
  68. /**
  69. * @param {Number} timeStamp 传入的时间戳
  70. * @param {Number} currentTime 当前时间时间戳
  71. * @returns {Boolean} 传入的时间戳是否早于当前时间戳
  72. */
  73. const isEarly = (timeStamp, currentTime) => {
  74. return timeStamp < currentTime
  75. }
  76. /**
  77. * @param {Number} num 数值
  78. * @returns {String} 处理后的字符串
  79. * @description 如果传入的数值小于10,即位数只有1位,则在前面补充0
  80. */
  81. const getHandledValue = num => {
  82. return num < 10 ? '0' + num : num
  83. }
  84. /**
  85. * @param {Number} timeStamp 传入的时间戳
  86. * @param {Number} startType 要返回的时间字符串的格式类型,传入'year'则返回年开头的完整时间
  87. */
  88. const getDate = (timeStamp, startType) => {
  89. const d = new Date(timeStamp * 1000)
  90. const year = d.getFullYear()
  91. const month = getHandledValue(d.getMonth() + 1)
  92. const date = getHandledValue(d.getDate())
  93. const hours = getHandledValue(d.getHours())
  94. const minutes = getHandledValue(d.getMinutes())
  95. const second = getHandledValue(d.getSeconds())
  96. let resStr = ''
  97. if (startType === 'year') resStr = year + '-' + month + '-' + date + ' ' + hours + ':' + minutes + ':' + second
  98. else resStr = month + '-' + date + ' ' + hours + ':' + minutes
  99. return resStr
  100. }
  101. /**
  102. * @param {Number} timeStamp 传入的时间戳
  103. * @param {Number} fmt 格式化字符串
  104. */
  105. export const formtDate = (timeStamp, fmt) => {
  106. const d = new Date(timeStamp)
  107. var o = {
  108. 'M+': d.getMonth() + 1, // 月份
  109. 'd+': d.getDate(), // 日
  110. 'h+': d.getHours(), // 小时
  111. 'm+': d.getMinutes(), // 分
  112. 's+': d.getSeconds(), // 秒
  113. 'q+': Math.floor((d.getMonth() + 3) / 3), // 季度
  114. 'S': d.getMilliseconds() // 毫秒
  115. }
  116. if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (d.getFullYear() + '').substr(4 - RegExp.$1.length))
  117. for (var k in o) { if (new RegExp('(' + k + ')').test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length))) }
  118. return fmt
  119. }
  120. // 获取三个月后的时间戳
  121. export const getThreeMonthsAfter = (dtstr) => {
  122. var s = dtstr.split('-')
  123. var yy = parseInt(s[0])
  124. var mm = parseInt(s[1])
  125. var dd = parseInt(s[2])
  126. var dt = new Date(yy, mm + 2, dd)
  127. return dt.valueOf()
  128. }
  129. /**
  130. * @param {String|Number} timeStamp 时间戳
  131. * @returns {String} 相对时间字符串
  132. */
  133. export const getRelativeTime = timeStamp => {
  134. // 判断当前传入的时间戳是秒格式还是毫秒
  135. const IS_MILLISECOND = isMillisecond(timeStamp)
  136. // 如果是毫秒格式则转为秒格式
  137. if (IS_MILLISECOND) Math.floor(timeStamp /= 1000)
  138. // 传入的时间戳可以是数值或字符串类型,这里统一转为数值类型
  139. timeStamp = Number(timeStamp)
  140. // 获取当前时间时间戳
  141. const currentTime = Math.floor(Date.parse(new Date()) / 1000)
  142. // 判断传入时间戳是否早于当前时间戳
  143. const IS_EARLY = isEarly(timeStamp, currentTime)
  144. // 获取两个时间戳差值
  145. let diff = currentTime - timeStamp
  146. // 如果IS_EARLY为false则差值取反
  147. if (!IS_EARLY) diff = -diff
  148. let resStr = ''
  149. const dirStr = IS_EARLY ? '前' : '后'
  150. // 少于等于59秒
  151. if (diff <= 59) resStr = diff + '秒' + dirStr
  152. // 多于59秒,少于等于59分钟59秒
  153. else if (diff > 59 && diff <= 3599) resStr = Math.floor(diff / 60) + '分钟' + dirStr
  154. // 多于59分钟59秒,少于等于23小时59分钟59秒
  155. else if (diff > 3599 && diff <= 86399) resStr = Math.floor(diff / 3600) + '小时' + dirStr
  156. // 多于23小时59分钟59秒,少于等于29天59分钟59秒
  157. else if (diff > 86399 && diff <= 2623859) resStr = Math.floor(diff / 86400) + '天' + dirStr
  158. // 多于29天59分钟59秒,少于364天23小时59分钟59秒,且传入的时间戳早于当前
  159. else if (diff > 2623859 && diff <= 31567859 && IS_EARLY) resStr = getDate(timeStamp)
  160. else resStr = getDate(timeStamp, 'year')
  161. return resStr
  162. }
  163. // 日期格式化
  164. export const formatSubmitDate = (val, type) => {
  165. if (val == null || val == '' || val == undefined) {
  166. return ''
  167. } else {
  168. const _date = new Date(val)
  169. const _year = _date.getFullYear()
  170. const _montn = (_date.getMonth() + 1) < 10 ? '0' + (_date.getMonth() + 1) : (_date.getMonth() + 1)
  171. const _day = _date.getDate() < 10 ? '0' + _date.getDate() : _date.getDate()
  172. const _hour = _date.getHours() < 10 ? '0' + _date.getHours() : _date.getHours()
  173. const _minutes = _date.getMinutes() < 10 ? '0' + _date.getMinutes() : _date.getMinutes()
  174. const _seconds = _date.getSeconds() < 10 ? '0' + _date.getSeconds() : _date.getSeconds()
  175. if (type == 'minutes') return _year + '-' + _montn + '-' + _day + ' ' + _hour + ':' + _minutes
  176. else if (type == 'seconds') return _year + '-' + _montn + '-' + _day + ' ' + _hour + ':' + _minutes + ':' + _seconds
  177. else return _year + '-' + _montn + '-' + _day
  178. }
  179. }
  180. // 正则验证车牌,验证通过返回true,不通过返回false
  181. export const isLicensePlate = function (str) {
  182. return /^(([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z](([0-9]{5}[DF])|([DF]([A-HJ-NP-Z0-9])[0-9]{4})))|([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳使领]))$/.test(str)
  183. }
  184. // 车牌可输入字符
  185. export const isCarNumber = function (str) {
  186. let _value = str + ''
  187. _value = _value.replace(/[^\w\.挂学警港澳使领]/ig, '')
  188. return _value
  189. }
  190. // 小数点后两位
  191. export const numberToFixed = function (val, num) {
  192. let _value = val + ''
  193. _value = _value.replace(/[^\d.]/g, '')// 清楚数字和.以外的字数
  194. _value = _value.replace(/^\./g, '')
  195. _value = _value.replace(/\.{2,}/g, '')// 保留第一个,清楚多余的
  196. if (num == 1)_value = _value.replace(/^(\-)*(\d+)\.(\d).*$/, '$1$2.$3')
  197. else if (num == 3)_value = _value.replace(/^(\-)*(\d+)\.(\d\d\d).*$/, '$1$2.$3')
  198. else if (num == 4)_value = _value.replace(/^(\-)*(\d+)\.(\d\d\d\d).*$/, '$1$2.$3')
  199. else if (num == 5)_value = _value.replace(/^(\-)*(\d+)\.(\d\d\d\d\d).*$/, '$1$2.$3')
  200. else if (num == 0)_value = _value.replace(/^(\-)*(\d+)\.*$/, '$1$2')
  201. else _value = _value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3')
  202. return _value
  203. }
  204. // 保留decimal位小数(不四舍五入) num 数值,decimal要保留的小数位数
  205. export const formatDecimal = function (num, decimal) {
  206. num = num.toString()
  207. const index = num.indexOf('.')
  208. if (index !== -1) {
  209. num = num.substring(0, decimal + index + 1)
  210. } else {
  211. num = num.substring(0)
  212. }
  213. return parseFloat(num).toFixed(decimal)
  214. }
  215. // 处理数字千位分隔符 num 数值,decimal要保留的小数位数
  216. export const toThousands = (num, decimal) => {
  217. if (num == undefined) {
  218. return '--'
  219. }
  220. num = formatDecimal(num, decimal||decimal==0 ? decimal : 2)
  221. return (decimal!=0?'¥':'') + num.toString().replace(/\d+/, function (n) { // 先提取整数部分
  222. return n.replace(/(\d)(?=(\d{3})+$)/g, function ($1) {
  223. return $1 + ','
  224. })
  225. })
  226. }
  227. // 只能输入数字
  228. export const justNumber = function (val) {
  229. let _value = val + ''
  230. _value = _value.replace(/\D/g, '')
  231. return _value
  232. }
  233. /**
  234. * @returns {String} 当前浏览器名称
  235. */
  236. export const getExplorer = () => {
  237. const ua = window.navigator.userAgent
  238. const isExplorer = (exp) => {
  239. return ua.indexOf(exp) > -1
  240. }
  241. if (isExplorer('MSIE')) return 'IE'
  242. else if (isExplorer('Firefox')) return 'Firefox'
  243. else if (isExplorer('Chrome')) return 'Chrome'
  244. else if (isExplorer('Opera')) return 'Opera'
  245. else if (isExplorer('Safari')) return 'Safari'
  246. }
  247. /**
  248. * @description 绑定事件 on(element, event, handler)
  249. */
  250. export const on = (function () {
  251. if (document.addEventListener) {
  252. return function (element, event, handler) {
  253. if (element && event && handler) {
  254. element.addEventListener(event, handler, false)
  255. }
  256. }
  257. } else {
  258. return function (element, event, handler) {
  259. if (element && event && handler) {
  260. element.attachEvent('on' + event, handler)
  261. }
  262. }
  263. }
  264. })()
  265. /**
  266. * @description 解绑事件 off(element, event, handler)
  267. */
  268. export const off = (function () {
  269. if (document.removeEventListener) {
  270. return function (element, event, handler) {
  271. if (element && event) {
  272. element.removeEventListener(event, handler, false)
  273. }
  274. }
  275. } else {
  276. return function (element, event, handler) {
  277. if (element && event) {
  278. element.detachEvent('on' + event, handler)
  279. }
  280. }
  281. }
  282. })()
  283. /**
  284. * 判断一个对象是否存在key,如果传入第二个参数key,则是判断这个obj对象是否存在key这个属性
  285. * 如果没有传入key这个参数,则判断obj对象是否有键值对
  286. */
  287. export const hasKey = (obj, key) => {
  288. if (key) return key in obj
  289. else {
  290. const keysArr = Object.keys(obj)
  291. return keysArr.length
  292. }
  293. }
  294. /**
  295. * @param {*} obj1 对象
  296. * @param {*} obj2 对象
  297. * @description 判断两个对象是否相等,这两个对象的值只能是数字或字符串
  298. */
  299. export const objEqual = (obj1, obj2) => {
  300. const keysArr1 = Object.keys(obj1)
  301. const keysArr2 = Object.keys(obj2)
  302. if (keysArr1.length !== keysArr2.length) return false
  303. else if (keysArr1.length === 0 && keysArr2.length === 0) return true
  304. /* eslint-disable-next-line */
  305. else return !keysArr1.some(key => obj1[key] != obj2[key])
  306. }
  307. /*
  308. * @param {*} id 数字
  309. * @param {*} list 数组
  310. * @description 根据id从数组列表中删除某一项
  311. */
  312. export const removeListById = (id, list) => {
  313. list.splice(list.findIndex(item => item.id === id), 1)
  314. }
  315. /**
  316. * @param {*} obj1 对象
  317. * @param {*} obj2 对象
  318. * @description 遍历赋值
  319. */
  320. export const objExtend = (obj1, obj2) => {
  321. for (var a in obj1) {
  322. obj2[a] = obj1[a]
  323. }
  324. return obj2
  325. }
  326. /**
  327. * @param {*} obj 对象
  328. * @description 浅拷贝
  329. */
  330. export const cloneObj = (obj) => {
  331. const ret = {}
  332. for (var a in obj) {
  333. ret[a] = obj[a]
  334. }
  335. return ret
  336. }
  337. /**
  338. * 校验身份证号合法性
  339. */
  340. export const checkIdNumberValid = (tex) => {
  341. // var tip = '输入的身份证号有误,请检查后重新输入!'
  342. let num = tex
  343. num = num.toUpperCase()
  344. const len = num.length
  345. let re
  346. if (len == 0) return true
  347. // 身份证号码为15位或者18位,15位时全为数字,18位前17位为数字,最后一位是校验位,可能为数字或字符X。
  348. if (!(/(^\d{15}$)|(^\d{17}([0-9]|X)$)/.test(num))) {
  349. return false
  350. }
  351. // 验证前两位地区是否有效
  352. const aCity = { 11: '北京',
  353. 12: '天津',
  354. 13: '河北',
  355. 14: '山西',
  356. 15: '内蒙古',
  357. 21: '辽宁',
  358. 22: '吉林',
  359. 23: '黑龙江',
  360. 31: '上海',
  361. 32: '江苏',
  362. 33: '浙江',
  363. 34: '安徽',
  364. 35: '福建',
  365. 36: '江西',
  366. 37: '山东',
  367. 41: '河南',
  368. 42: '湖北',
  369. 43: '湖南',
  370. 44: '广东',
  371. 45: '广西',
  372. 46: '海南',
  373. 50: '重庆',
  374. 51: '四川',
  375. 52: '贵州',
  376. 53: '云南',
  377. 54: '西藏',
  378. 61: '陕西',
  379. 62: '甘肃',
  380. 63: '青海',
  381. 64: '宁夏',
  382. 65: '新疆',
  383. 71: '台湾',
  384. 81: '香港',
  385. 82: '澳门',
  386. 91: '国外' }
  387. if (aCity[parseInt(num.substr(0, 2))] == null) {
  388. return false
  389. }
  390. // 当身份证为15位时的验证出生日期。
  391. if (len == 15) {
  392. re = new RegExp(/^(\d{6})(\d{2})(\d{2})(\d{2})(\d{3})$/)
  393. const arrSplit = num.match(re)
  394. // 检查生日日期是否正确
  395. const dtmBirth = new Date('19' + arrSplit[2] + '/' + arrSplit[3] + '/' + arrSplit[4])
  396. const bGoodDay = (dtmBirth.getYear() == Number(arrSplit[2])) && ((dtmBirth.getMonth() + 1) == Number(arrSplit[3])) && (dtmBirth.getDate() == Number(arrSplit[4]))
  397. if (!bGoodDay) {
  398. return false
  399. }
  400. }
  401. // 当身份证号为18位时,校验出生日期和校验位。
  402. if (len == 18) {
  403. re = new RegExp(/^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/)
  404. const arrSplit = num.match(re)
  405. // 检查生日日期是否正确
  406. const dtmBirth = new Date(arrSplit[2] + '/' + arrSplit[3] + '/' + arrSplit[4])
  407. const bGoodDay = (dtmBirth.getFullYear() == Number(arrSplit[2])) && ((dtmBirth.getMonth() + 1) == Number(arrSplit[3])) && (dtmBirth.getDate() == Number(arrSplit[4]))
  408. if (!bGoodDay) {
  409. return false
  410. } else {
  411. // 检验18位身份证的校验码是否正确。
  412. // 校验位按照ISO 7064:1983.MOD 11-2的规定生成,X可以认为是数字10。
  413. let valnum
  414. const arrInt = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
  415. const arrCh = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']
  416. let nTemp = 0
  417. let i
  418. for (i = 0; i < 17; i++) {
  419. nTemp += num.substr(i, 1) * arrInt[i]
  420. }
  421. valnum = arrCh[nTemp % 11]
  422. if (valnum != num.substr(17, 1)) {
  423. return false
  424. }
  425. }
  426. }
  427. return true
  428. }