tools.js 15 KB

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