tools.js 15 KB

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