sun.js 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569
  1. /**
  2. * sunui-extends.js for sunui
  3. *
  4. * author:1940694428@qq.com
  5. *
  6. * 2020.05.12
  7. *
  8. * **/
  9. // const regeneratorRuntime = require("regenerator-runtime");
  10. module.exports = {
  11. version: "last update:2020.05.12 , veriosn:1.0.0",
  12. /**
  13. * 计算两个日期时间相差的年数、月数、天数、小时数、分钟数、秒数
  14. * DIFFTIME(开始时间,结束时间,[单位]),单位可以是 "y" 、"M"、"d"、"h"、"m"、"s"'
  15. * console.log(DIFFTIME('2019-6-30 13:20:00', '2020-10-01 11:20:32', 's'))
  16. */
  17. getDay(day) {
  18. var today = new Date();
  19. var targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day;
  20. today.setTime(targetday_milliseconds); //注意,这行是关键代码
  21. var tYear = today.getFullYear();
  22. var tMonth = today.getMonth();
  23. var tDate = today.getDate();
  24. tMonth = this.doHandleMonth(tMonth + 1);
  25. tDate = this.doHandleMonth(tDate);
  26. return tYear + "-" + tMonth + "-" + tDate;
  27. },
  28. doHandleMonth(month) {
  29. var m = month;
  30. if (month.toString().length == 1) {
  31. m = "0" + month;
  32. }
  33. return m;
  34. },
  35. tab(time,date1) {
  36. var sDate = new Date(time);
  37. var oDate1 = new Date(date1);
  38. // var oDate2 = new Date(date2);
  39. console.log('1111111', time,date1);
  40. if (sDate.getTime() < oDate1.getTime()) {
  41. console.log('第一个大', sDate.getTime(), oDate1.getTime());
  42. return true;
  43. } else {
  44. console.log('第二个大', sDate.getTime(), oDate1.getTime());
  45. return false;
  46. }
  47. },
  48. DIFFTIME(startTime, endTime, unit) {
  49. if (!startTime || !endTime) {
  50. return '';
  51. }
  52. // 判断当前月天数
  53. function getDays(mouth, year) {
  54. let days = 30;
  55. if (mouth === 2) {
  56. days = year % 4 === 0 ? 29 : 28;
  57. } else if (
  58. mouth === 1 ||
  59. mouth === 3 ||
  60. mouth === 5 ||
  61. mouth === 7 ||
  62. mouth === 8 ||
  63. mouth === 10 ||
  64. mouth === 12
  65. ) {
  66. // 月份为:1,3,5,7,8,10,12 时,为大月.则天数为31;
  67. days = 31;
  68. }
  69. return days;
  70. }
  71. const start = new Date(startTime);
  72. const end = new Date(endTime);
  73. // 计算时间戳的差
  74. const diffValue = end - start;
  75. // 获取年
  76. const startYear = start.getFullYear();
  77. const endYear = end.getFullYear();
  78. // 获取月
  79. const startMouth = start.getMonth() + 1;
  80. const endMouth = end.getMonth() + 1;
  81. // 获取日
  82. const startDay = start.getDate();
  83. const endDay = end.getDate();
  84. // 获取小时
  85. const startHours = start.getHours();
  86. const endHours = end.getHours();
  87. // 获取分
  88. const startMinutes = start.getMinutes();
  89. const endMinutes = end.getMinutes();
  90. // 获取秒
  91. const startSeconds = start.getSeconds();
  92. const endSeconds = end.getSeconds();
  93. // 下方注释两行为调试用
  94. // console.log('start:', startYear, startMouth, startDay, startHours, startMinutes, startSeconds)
  95. // console.log('end:', endYear, endMouth, endDay, endHours, endMinutes, endSeconds)
  96. if (unit === 'y' || unit === 'M') {
  97. // 相差年份月份
  98. const diffYear = endYear - startYear;
  99. // 获取当前月天数
  100. const startDays = getDays(startMouth, startYear);
  101. const endDays = getDays(endMouth, endYear);
  102. const diffStartMouth =
  103. (startDays -
  104. (startDay + (startHours * 60 + startMinutes + startSeconds / 60) / 60 / 24 - 1)) /
  105. startDays;
  106. const diffEndMouth =
  107. (endDay + (endHours * 60 + endMinutes + endSeconds / 60) / 60 / 24 - 1) / endDays;
  108. const diffMouth =
  109. diffStartMouth + diffEndMouth + (12 - startMouth - 1) + endMouth + (diffYear - 1) * 12;
  110. if (unit === 'y') {
  111. return Math.floor((diffMouth / 12) * 100) / 100;
  112. } else {
  113. return diffMouth;
  114. }
  115. } else if (unit === 'd') {
  116. const d = parseInt(diffValue / 1000 / 60 / 60 / 24);
  117. return d;
  118. } else if (unit === 'h') {
  119. const h = parseInt(diffValue / 1000 / 60 / 60);
  120. return h;
  121. } else if (unit === 'm') {
  122. const m = parseInt(diffValue / 1000 / 60);
  123. return m;
  124. } else if (unit === 's') {
  125. const s = parseInt(diffValue / 1000);
  126. return s;
  127. } else {
  128. console.log('请输入正确的单位');
  129. }
  130. },
  131. // 传入2021-09-14 13:20:40 返回['2021-09-14','13:20:40']
  132. yearAndDate(date) {
  133. return date.trim().split(' ');
  134. },
  135. /*判断一个元素是否在数组中*/
  136. contains(arr, val) {
  137. return arr.indexOf(val) != -1 ? true : false;
  138. },
  139. // 查找数组最小值
  140. arrayMin(arr) {
  141. return Math.min(...arr);
  142. },
  143. // 从数组中移除 falsey 值
  144. arrayCompact(arr) {
  145. return arr.filter(Boolean);
  146. },
  147. // 数组中重复的值计数
  148. arrCount(arr, value) {
  149. return arr.reduce((a, v) => v === value ? a + 1 : a + 0, 0);
  150. },
  151. // 返回两个数组差异
  152. arrayDiff(a, b) {
  153. const s = new Set(b);
  154. return a.filter(x => !s.has(x));
  155. },
  156. // 判断数组元素是否重复
  157. isArrRepeat(arr) {
  158. let _arr = arr.sort();
  159. console.log(_arr);
  160. for (let i = 0; i < _arr.length; i++) {
  161. if (_arr[i] === _arr[i + 1]) {
  162. return true;
  163. }
  164. }
  165. return false;
  166. },
  167. /**
  168. * @param {arr} 数组
  169. * @param {fn} 回调函数
  170. * @return {undefined}
  171. */
  172. each(arr, fn) {
  173. fn = fn || Function;
  174. let a = [];
  175. let args = Array.prototype.slice.call(arguments, 1);
  176. for (let i = 0; i < arr.length; i++) {
  177. let res = fn.apply(arr, [arr[i], i].concat(args));
  178. if (res != null) a.push(res);
  179. }
  180. },
  181. /**
  182. * @param {arr} 数组
  183. * @param {fn} 回调函数
  184. * @param {thisObj} this指向
  185. * @return {Array}
  186. */
  187. map(arr, fn, thisObj) {
  188. let scope = thisObj || window;
  189. let a = [];
  190. for (let i = 0, j = arr.length; i < j; ++i) {
  191. let res = fn.call(scope, arr[i], i, this);
  192. if (res != null) a.push(res);
  193. }
  194. return a;
  195. },
  196. /**
  197. * @param {arr} 数组
  198. * @param {type} 1:从小到大 2:从大到小 3:随机
  199. * @return {Array}
  200. */
  201. sort(arr, type = 1) {
  202. return arr.sort((a, b) => {
  203. switch (type) {
  204. case 1:
  205. return a - b;
  206. case 2:
  207. return b - a;
  208. case 3:
  209. return Math.random() - 0.5;
  210. default:
  211. return arr;
  212. }
  213. })
  214. },
  215. /*去重*/
  216. arrayUnique(arr) {
  217. if (Array.hasOwnProperty('from')) {
  218. return Array.from(new Set(arr));
  219. } else {
  220. let n = {},
  221. r = [];
  222. for (let i = 0; i < arr.length; i++) {
  223. if (!n[arr[i]]) {
  224. n[arr[i]] = true;
  225. r.push(arr[i]);
  226. }
  227. }
  228. return r;
  229. }
  230. // 注:上面 else 里面的排重并不能区分 2 和 '2',但能减少用indexOf带来的性能
  231. /* 正确排重
  232. if ( Array.hasOwnProperty('from') ) {
  233. return Array.from(new Set(arr))
  234. }else{
  235. let r = [], NaNBol = true
  236. for(let i=0; i < arr.length; i++) {
  237. if (arr[i] !== arr[i]) {
  238. if (NaNBol && r.indexOf(arr[i]) === -1) {
  239. r.push(arr[i])
  240. NaNBol = false
  241. }
  242. }else{
  243. if(r.indexOf(arr[i]) === -1) r.push(arr[i])
  244. }
  245. }
  246. return r
  247. }
  248. */
  249. },
  250. /*求两个集合的并集*/
  251. union(a, b) {
  252. let newArr = a.concat(b);
  253. return this.arrayUnique(newArr);
  254. },
  255. /*求两个集合的交集*/
  256. intersect(a, b) {
  257. let _this = this;
  258. a = this.arrayUnique(a);
  259. return this.map(a, function(o) {
  260. return _this.contains(b, o) ? o : null;
  261. });
  262. },
  263. /*删除其中一个元素*/
  264. arrayRemove(arr, ele) {
  265. let index = arr.indexOf(ele);
  266. if (index > -1) {
  267. arr.splice(index, 1);
  268. }
  269. return arr;
  270. },
  271. /*删除某一项数组*/
  272. arraySplice(arr, index) {
  273. arr.splice(Number(index), 1);
  274. return arr;
  275. },
  276. /*将类数组转换为数组的方法*/
  277. formArray(ary) {
  278. let arr = [];
  279. if (Array.isArray(ary)) {
  280. arr = ary;
  281. } else {
  282. arr = Array.prototype.slice.call(ary);
  283. };
  284. return arr;
  285. },
  286. /*最大值*/
  287. max(arr) {
  288. return Math.max.apply(null, arr);
  289. },
  290. /*最小值*/
  291. min(arr) {
  292. return Math.min.apply(null, arr);
  293. },
  294. /*求和*/
  295. sum(arr) {
  296. return arr.reduce((pre, cur) => {
  297. return pre + cur
  298. });
  299. },
  300. /*平均值*/
  301. average(arr) {
  302. return this.sum(arr) / arr.length;
  303. },
  304. /**
  305. * 设置和获取同步缓存
  306. * @param {String} key 设置key
  307. * @param {Any} value 缓存任意值
  308. * @return {Any} 返回版本信息
  309. */
  310. setCache(key, value) {
  311. wx.setStorageSync(key, JSON.stringify(value));
  312. },
  313. getCache(key) {
  314. try {
  315. return JSON.parse(wx.getStorageSync(key));
  316. } catch (e) {
  317. //TODO handle the exception
  318. return wx.getStorageSync(key);
  319. }
  320. },
  321. removeCache(key) {
  322. wx.removeStorageSync(key);
  323. },
  324. clearCache() {
  325. wx.clearStorageSync();
  326. },
  327. // 获取是否闰年
  328. dateLeapYear() {
  329. let year = new Date().getFullYear();
  330. return ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
  331. },
  332. // 获取当前时间戳 - 13位转为10位,然后*1000再parseInt
  333. dateStamp(digits = 10) {
  334. digits = Number(digits);
  335. switch (digits) {
  336. case 10:
  337. return Math.round(new Date().getTime() / 1000).toString();
  338. case 13:
  339. return new Date().getTime().toString();
  340. }
  341. },
  342. /**
  343. * 类型判断
  344. * @param {String,Number} number 传入的数值
  345. * @return {String} 返回字符串
  346. */
  347. toDigit(any) {
  348. return any.toString().replace(/^(\d)$/, `0$1`);
  349. },
  350. /**
  351. *秒转成分钟: 如 100 => 01:40
  352. *
  353. * @param {*} sec
  354. * @returns
  355. */
  356. dateStoM(sec) {
  357. const MINUTE = 60;
  358. const minute = Math.floor(sec / MINUTE);
  359. const surplusSec = sec % MINUTE;
  360. return `${this.toDigit(minute)}:${this.toDigit(surplusSec)}`;
  361. },
  362. /**
  363. * 传入13位时间戳获取距离当前时间
  364. * @param {*} sec
  365. * @return {String} 3天前 返回距离时间具体描述
  366. */
  367. dateDistance(timestamp) {
  368. let publishTime = Number(timestamp) / 1000,
  369. date = new Date(publishTime * 1000),
  370. Y = this.toDigit(date.getFullYear()),
  371. M = this.toDigit(date.getMonth() + 1),
  372. D = this.toDigit(date.getDate()),
  373. H = this.toDigit(date.getHours()),
  374. m = this.toDigit(date.getMinutes()),
  375. s = this.toDigit(date.getSeconds());
  376. let nowTime = new Date().getTime() / 1000,
  377. diffValue = nowTime - publishTime,
  378. diff_days = parseInt(diffValue / 86400),
  379. diff_hours = parseInt(diffValue / 3600),
  380. diff_minutes = parseInt(diffValue / 60),
  381. diff_secodes = parseInt(diffValue);
  382. if (diff_days > 0 && diff_days < 3) {
  383. return diff_days + "天前";
  384. } else if (diff_days <= 0 && diff_hours > 0) {
  385. return diff_hours + "小时前";
  386. } else if (diff_hours <= 0 && diff_minutes > 0) {
  387. return diff_minutes + "分钟前";
  388. } else if (diff_secodes < 60) {
  389. if (diff_secodes <= 0) {
  390. return "刚刚";
  391. } else {
  392. return diff_secodes + "秒前";
  393. }
  394. } else if (diff_days >= 3 && diff_days < 30) {
  395. return M + '-' + D + ' ' + H + ':' + m;
  396. } else if (diff_days >= 30) {
  397. return Y + '-' + M + '-' + D + ' ' + H + ':' + m;
  398. }
  399. },
  400. /**
  401. * 获取当天周几
  402. * @param {}
  403. * @return {String} "星期x" 返回周几
  404. */
  405. dateWeek() {
  406. let day = new Date().getDay();
  407. let week = new Array("星期日", "星期一", "星期二", "星期三", "星期四", "星期五");
  408. return week[day];
  409. },
  410. /**
  411. * 获取当天是否周六周日
  412. * @param {}
  413. * @return {Boolean} true/false 返回是否周六周日
  414. */
  415. dateWeekend() {
  416. let _date = new Date();
  417. let _nowTime = _date.getTime();
  418. let _week = _date.getDay();
  419. let _yearMonthDay =
  420. `${_date.getFullYear()}-${_date.getMonth()+1>=10?_date.getMonth()+1:'0'+_date.getMonth()+1}-${_date.getDate()>=10?_date.getDate():'0'+_date.getDate()}`;
  421. let _dayLongTime = 24 * 60 * 60 * 1000;
  422. let _furtureSundayTimes = _nowTime + (7 - _week) * _dayLongTime;
  423. let _furtureSaturdayTimes = _nowTime + (6 - _week) * _dayLongTime;
  424. let _mealSunDay;
  425. let _mealSaturDay;
  426. _furtureSundayTimes = new Date(_furtureSundayTimes);
  427. _furtureSaturdayTimes = new Date(_furtureSaturdayTimes);
  428. let _satYear = _furtureSaturdayTimes.getFullYear();
  429. let _satMonth = _furtureSaturdayTimes.getMonth() + 1;
  430. let _satDay = _furtureSaturdayTimes.getDate();
  431. let _sunYear = _furtureSundayTimes.getFullYear();
  432. let _sunMonth = _furtureSundayTimes.getMonth() + 1;
  433. let _sunDay = _furtureSundayTimes.getDate();
  434. _satMonth = _satMonth >= 10 ? _satMonth : '0' + _satMonth;
  435. _satDay = _satDay >= 10 ? _satDay : '0' + _satDay;
  436. _sunMonth = _sunMonth >= 10 ? _sunMonth : '0' + _sunMonth;
  437. _sunDay = _sunDay >= 10 ? _sunDay : '0' + _sunDay;
  438. _mealSunDay = _satYear + '-' + _satMonth + '-' + _satDay;
  439. _mealSaturDay = _sunYear + '-' + _sunMonth + '-' + _sunDay;
  440. let _weekendDay = [_mealSunDay, _mealSaturDay];
  441. let _isWeekend = _weekendDay.indexOf(_yearMonthDay) != -1;
  442. // 最近的周六/周日 _weekendDay. _isWeekend:true | false
  443. return _isWeekend;
  444. },
  445. /**
  446. * 传入13位时间戳
  447. * @param {String,Number} timestamp "1589257080657"
  448. * @param {String} format "Y-M-D Y-M-D-h-m-s"
  449. * @return {String} "2020*01*05 10:00"
  450. */
  451. dateFormat(timestamp, format) {
  452. format = format || `Y-M-D`;
  453. const cur = Number(timestamp) ? new Date(Number(timestamp)) : new Date();
  454. const year = cur.getFullYear();
  455. const month = this.toDigit(cur.getMonth() + 1);
  456. const day = this.toDigit(cur.getDate());
  457. const hour = this.toDigit(cur.getHours());
  458. const minute = this.toDigit(cur.getMinutes());
  459. const second = this.toDigit(cur.getSeconds());
  460. return format.replace(/Y|M|D|h|m|s/g, function(matches) {
  461. return ({
  462. Y: year,
  463. M: month,
  464. D: day,
  465. h: hour,
  466. m: minute,
  467. s: second
  468. })[matches];
  469. });
  470. },
  471. /**
  472. * 格式化时间
  473. *
  474. * @param {time} 时间
  475. * @param {cFormat} 格式
  476. * @return {String} 字符串
  477. *
  478. * @example formatTime('2018-1-29', '{y}/{m}/{d} {h}:{i}:{s}') // -> 2018/01/29 00:00:00
  479. */
  480. formatTime(time, cFormat) {
  481. if (arguments.length === 0) return null
  482. if ((time + '').length === 10) {
  483. time = +time * 1000
  484. }
  485. let format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}',
  486. date
  487. if (typeof time === 'object') {
  488. date = time
  489. } else {
  490. date = new Date(time)
  491. }
  492. let formatObj = {
  493. y: date.getFullYear(),
  494. m: date.getMonth() + 1,
  495. d: date.getDate(),
  496. h: date.getHours(),
  497. i: date.getMinutes(),
  498. s: date.getSeconds(),
  499. a: date.getDay()
  500. }
  501. let time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
  502. let value = formatObj[key]
  503. if (key === 'a') return ['一', '二', '三', '四', '五', '六', '日'][value - 1]
  504. if (result.length > 0 && value < 10) {
  505. value = '0' + value
  506. }
  507. return value || 0
  508. })
  509. return time_str
  510. },
  511. /**
  512. * 返回指定长度的月份集合
  513. *
  514. * @param {time} 时间
  515. * @param {len} 长度
  516. * @param {direction} 方向: 1: 前几个月; 2: 后几个月; 3:前后几个月 默认 3
  517. * @return {Array} 数组
  518. *
  519. * @example dateMonths('2018-1-29', 6, 1) // -> ["2018-1", "2017-12", "2017-11", "2017-10", "2017-9", "2017-8", "2017-7"]
  520. */
  521. dateMonths(time, len, direction) {
  522. direction = isNaN(direction) ? 3 : direction;
  523. let mm = new Date(time).getMonth() + 1,
  524. yy = new Date(time).getFullYear(),
  525. index = mm;
  526. let cutMonth = function(index) {
  527. let arr
  528. if (direction === 1) {
  529. arr = formatPre(index).reverse()
  530. } else if (direction === 2) {
  531. arr = formatNext(index)
  532. } else {
  533. arr = formatPre(index).reverse().slice(len / 2).concat(formatNext(index).slice(1, len / 2 +
  534. 1))
  535. }
  536. return arr.sort(function(t1, t2) {
  537. return new Date(t1).getTime() - new Date(t2).getTime()
  538. })
  539. }
  540. let formatPre = function(index) {
  541. let currNum = index,
  542. preNum = 0,
  543. currArr = [],
  544. preArr = []
  545. if (index - len < 0) {
  546. preNum = len - currNum
  547. }
  548. for (let i = 0; i < currNum; i++) {
  549. currArr.push([yy + '-' + (currNum - i)])
  550. }
  551. for (let i = 1; i <= preNum; i++) {
  552. preArr.push([(yy - Math.ceil(i / 12)) + '-' + (12 - (i - 1) % 12)])
  553. }
  554. return currArr.concat(preArr)
  555. }
  556. let formatNext = function(index) {
  557. let currNum = 12 - index,
  558. nextNum = 0,
  559. currArr = [],
  560. nextArr = []
  561. if (len - currNum > 0) {
  562. nextNum = len - currNum
  563. }
  564. for (let i = 0; i <= currNum; i++) {
  565. currArr.push([yy + '-' + (index + i)])
  566. }
  567. for (let i = 1; i < nextNum; i++) {
  568. nextArr.push([(yy + Math.ceil(i / 12)) + '-' + (i % 13 === 0 ? 1 : i % 13)])
  569. }
  570. return currArr.concat(nextArr)
  571. }
  572. return cutMonth(index)
  573. },
  574. /**
  575. * 返回指定长度的天数集合
  576. *
  577. * @param {time} 时间
  578. * @param {len} 长度
  579. * @param {direction} 方向: 1: 前几天; 2: 后几天; 3:前后几天 默认 3
  580. * @return {Array} 数组
  581. *
  582. * @example dateDays('2018-1-29', 6) // -> ["2018-1-26", "2018-1-27", "2018-1-28", "2018-1-29", "2018-1-30", "2018-1-31", "2018-2-1"]
  583. */
  584. dateDays(time, len, diretion) {
  585. let tt = new Date(time)
  586. let getDay = function(day) {
  587. let t = new Date(time)
  588. t.setDate(t.getDate() + day)
  589. let m = t.getMonth() + 1
  590. return t.getFullYear() + '-' + m + '-' + t.getDate()
  591. }
  592. let arr = []
  593. if (diretion === 1) {
  594. for (let i = 1; i <= len; i++) {
  595. arr.unshift(getDay(-i))
  596. }
  597. } else if (diretion === 2) {
  598. for (let i = 1; i <= len; i++) {
  599. arr.push(getDay(i))
  600. }
  601. } else {
  602. for (let i = 1; i <= len; i++) {
  603. arr.unshift(getDay(-i))
  604. }
  605. arr.push(tt.getFullYear() + '-' + (tt.getMonth() + 1) + '-' + tt.getDate())
  606. for (let i = 1; i <= len; i++) {
  607. arr.push(getDay(i))
  608. }
  609. }
  610. return diretion === 1 ? arr.concat([tt.getFullYear() + '-' + (tt.getMonth() + 1) + '-' + tt
  611. .getDate()]) :
  612. diretion === 2 ? [tt.getFullYear() + '-' + (tt.getMonth() + 1) + '-' + tt.getDate()].concat(arr) :
  613. arr
  614. },
  615. /**
  616. * @param {s} 秒数
  617. * @return {String} 字符串
  618. *
  619. * @example formatHMS(3610) // -> 1h0m10s
  620. */
  621. dateStoH(s) {
  622. let str = ''
  623. if (s > 3600) {
  624. str = Math.floor(s / 3600) + 'h' + Math.floor(s % 3600 / 60) + 'm' + s % 60 + 's'
  625. } else if (s > 60) {
  626. str = Math.floor(s / 60) + 'm' + s % 60 + 's'
  627. } else {
  628. str = s % 60 + 's'
  629. }
  630. return str
  631. },
  632. /*获取某月有多少天*/
  633. dateMonthOfDay(timestamp) {
  634. let date = new Date(Number(timestamp))
  635. let year = date.getFullYear()
  636. let mouth = date.getMonth() + 1
  637. let days
  638. //当月份为二月时,根据闰年还是非闰年判断天数
  639. if (mouth == 2) {
  640. days = (year % 4 == 0 && year % 100 == 0 && year % 400 == 0) || (year % 4 == 0 && year % 100 != 0) ?
  641. 28 : 29
  642. } else if (mouth == 1 || mouth == 3 || mouth == 5 || mouth == 7 || mouth == 8 || mouth == 10 || mouth ==
  643. 12) {
  644. //月份为:1,3,5,7,8,10,12 时,为大月.则天数为31;
  645. days = 31
  646. } else {
  647. //其他月份,天数为:30.
  648. days = 30
  649. }
  650. return days
  651. },
  652. /*获取某年有多少天*/
  653. dateYearOfDay(time) {
  654. let firstDayYear = this.dateFirstDayOfYear(time);
  655. let lastDayYear = this.dateLastDayOfYear(time);
  656. let numSecond = (new Date(lastDayYear).getTime() - new Date(firstDayYear).getTime()) / 1000;
  657. return Math.ceil(numSecond / (24 * 3600));
  658. },
  659. /*获取某年的第一天*/
  660. dateFirstDayOfYear(time) {
  661. let year = new Date(time).getFullYear();
  662. return year + "-01-01 00:00:00";
  663. },
  664. /*获取某年最后一天*/
  665. dateLastDayOfYear(time) {
  666. let year = new Date(time).getFullYear();
  667. let dateString = year + "-12-01 00:00:00";
  668. let endDay = this.getMonthOfDay(dateString);
  669. return year + "-12-" + endDay + " 23:59:59";
  670. },
  671. /*获取某个日期是当年中的第几天*/
  672. dateDayOfYear(time) {
  673. let firstDayYear = this.dateFirstDayOfYear(time);
  674. let numSecond = (new Date(time).getTime() - new Date(firstDayYear).getTime()) / 1000;
  675. return Math.ceil(numSecond / (24 * 3600));
  676. },
  677. /*获取某个日期在这一年的第几周*/
  678. dateDayOfYearWeek(time) {
  679. let numdays = this.dateDayOfYear(time);
  680. return Math.ceil(numdays / 7);
  681. },
  682. /**
  683. * 是否对象
  684. * @param {Object} obj 传入对象
  685. * @return {Boolean} 返回true或false
  686. */
  687. isObject(obj) {
  688. return obj !== null && typeof obj === 'object';
  689. },
  690. /**
  691. * 是否正则表达式
  692. * @param {RegExp} v 传入正则表达式
  693. * @return {Boolean} 返回true或false
  694. */
  695. isRegExp(v) {
  696. return Object.prototype.toString.call(v) === '[object RegExp]';
  697. },
  698. /**
  699. * 是否未定义
  700. * @param {String} v 传入需要校验的值
  701. * @return {Boolean} 返回true或false
  702. */
  703. isUndef(v) {
  704. return v === undefined || v === null;
  705. },
  706. /**
  707. * 是否已定义
  708. * @param {String} v 传入需要校验的值
  709. * @return {Boolean} 返回true或false
  710. */
  711. isDef(v) {
  712. return v !== undefined && v !== null;
  713. },
  714. /**
  715. * 是否已定义
  716. * @param {String} v 传入需要校验的值
  717. * @return {Boolean} 返回true或false
  718. */
  719. isString(v) {
  720. return v.constructor == String;
  721. },
  722. /**
  723. * 是否已定义
  724. * @param {Number} v 传入需要校验的值
  725. * @return {Boolean} 返回true或false
  726. */
  727. isNumber(v) {
  728. return v.constructor == Number;
  729. },
  730. /**
  731. * 是否已定义
  732. * @param {Boolean} v 传入需要校验的值
  733. * @return {Boolean} 返回true或false
  734. */
  735. isBoolean(v) {
  736. return v.constructor == true;
  737. },
  738. /**
  739. * 是否已定义
  740. * @param {Function} v 传入需要校验的值
  741. * @return {Boolean} 返回true或false
  742. */
  743. isFunc(v) {
  744. return v.constructor == Function;
  745. },
  746. /**
  747. * 是否Array
  748. * @param {Array} v 传入需要校验的值
  749. * @return {Boolean} 返回true或false
  750. */
  751. isArray(v) {
  752. return Array.isArray(v);
  753. },
  754. // 是否为false - https://www.cnblogs.com/cisum/p/12072873.html
  755. isTrue(any) {
  756. let match = ['undefined', 'null', 'NaN', 'false', false, 0, undefined, NaN, ''];
  757. return match.indexOf(any) > -1 ? false : true;
  758. },
  759. /**
  760. * 是否存在空格
  761. * @param {Object} obj 传入需要校验的值
  762. * @return {Boolean} 返回true或false
  763. */
  764. isSpaceObject(obj) {
  765. return Object.keys(obj).length > 0 ? true : false;
  766. },
  767. /**
  768. * 是否存在空格
  769. * @param {String} str 传入需要校验的值
  770. * @return {Boolean} 返回true或false
  771. */
  772. isSpace(str) {
  773. return /\s/.test(str);
  774. },
  775. /**
  776. * 是否为符号
  777. * @param {Symbol} symbol 传入需要校验的值
  778. * @return {Boolean} 返回true或false
  779. */
  780. isSymbol(v) {
  781. return typeof v === 'symbol';
  782. },
  783. /**
  784. * [获取当前经纬度]
  785. * const map = await this.$map.latlng();
  786. * @return {Object}=>{lat:xx,lng:xx}
  787. */
  788. latlng: () => {
  789. return new Promise((resolve, reject) => {
  790. wx.getLocation({
  791. type: 'gcj02',
  792. success: res => {
  793. resolve({
  794. lat: res.latitude,
  795. lng: res.longitude
  796. });
  797. },
  798. fail: err => {
  799. reject(err);
  800. }
  801. });
  802. });
  803. },
  804. /**
  805. * [传入腾讯地图密钥以获取当前地理位置信息]
  806. * const map = await this.$map.location({lat:'xx',lng:'xx',key:'xxxx-xxxx'});
  807. *
  808. *
  809. * gcj02不支持国外腾讯地图
  810. *
  811. * @return {Object}
  812. */
  813. location: ({
  814. lat,
  815. lng,
  816. key
  817. }) => {
  818. return new Promise((resolve, reject) => {
  819. wx.request({
  820. url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${lat},${lng}&key=${key}`,
  821. method: 'GET',
  822. success: res => {
  823. res.data.status == 0 ? resolve(res.data.result) : reject(res.data
  824. .message);
  825. }
  826. });
  827. });
  828. },
  829. /**
  830. * [传入腾讯地图密钥以获取当前地理位置信息以及当地天气]
  831. * const weather = await this.$map.weather({key:xxxx-xxxx});
  832. * @return {Object}
  833. */
  834. weather: ({
  835. key
  836. }) => {
  837. return new Promise((resolve, reject) => {
  838. wx.getLocation({
  839. type: 'gcj02',
  840. success: res => {
  841. wx.request({
  842. url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${res.latitude},${res.longitude}&key=${key}`,
  843. method: 'GET',
  844. success: res => {
  845. if (res.data.message == 'query ok') {
  846. let address = res.data.result.address_component;
  847. wx.request({
  848. url: `https://wis.qq.com/weather/common`,
  849. method: 'GET',
  850. data: {
  851. source: 'xw',
  852. weather_type: 'observe|alarm|air|forecast_1h|forecast_24h|index|limit|tips|rise',
  853. province: `${address.province}`,
  854. city: `${address.city}`,
  855. county: `${address.district}`
  856. },
  857. success: res => {
  858. resolve(res.data.data);
  859. },
  860. fail: () => {
  861. reject(res.data.message);
  862. },
  863. complete: () => {}
  864. });
  865. }
  866. }
  867. });
  868. },
  869. fail: err => {
  870. reject(err);
  871. }
  872. });
  873. });
  874. },
  875. /**
  876. * [选择地图上的地址信息]
  877. * const map = await this.$map.chooseLocation({lat,lng});
  878. * @return {Object}
  879. */
  880. chooseLocation: ({
  881. lat,
  882. lng
  883. }) => {
  884. return new Promise((resolve, reject) => {
  885. wx.chooseLocation({
  886. latitude: lat,
  887. longitude: lng,
  888. success: res => {
  889. resolve(res);
  890. },
  891. fail: err => {
  892. reject(err);
  893. }
  894. });
  895. });
  896. },
  897. /**
  898. * [传入经纬度以及腾讯地图密钥获取对应地址信息]
  899. * const map = await this.$map.openLocation({lat:xx,lng:xx,key:'xx-xx'});
  900. * @return {Null}
  901. */
  902. openLocation: ({
  903. lat,
  904. lng,
  905. key
  906. }) => {
  907. return new Promise((resolve, reject) => {
  908. wx.request({
  909. url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${lat},${lng}&key=${key}`,
  910. method: 'GET',
  911. success: res => {
  912. try {
  913. wx.openLocation({
  914. latitude: res.data.result.location.lat,
  915. longitude: res.data.result.location.lng,
  916. name: res.data.result.ad_info.district,
  917. address: res.data.result.address,
  918. scale: 18
  919. });
  920. } catch (e) {
  921. //TODO handle the exception
  922. reject(res.data.message);
  923. }
  924. },
  925. fail: err => {
  926. reject(err);
  927. }
  928. });
  929. });
  930. },
  931. /*随机数范围*/
  932. random(min, max) {
  933. if (arguments.length === 2) {
  934. return Math.floor(min + Math.random() * ((max + 1) - min))
  935. } else {
  936. return null;
  937. }
  938. },
  939. moneyFormat(number, decimals, dec_point, thousands_sep) {
  940. /*
  941. * 参数说明:
  942. * number:要格式化的数字
  943. * decimals:保留几位小数
  944. * dec_point:小数点符号
  945. * thousands_sep:千分位符号
  946. * */
  947. number = (number + '').replace(/[^0-9+-Ee.]/g, '');
  948. var n = !isFinite(+number) ? 0 : +number,
  949. prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
  950. sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
  951. dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
  952. s = '',
  953. toFixedFix = function(n, prec) {
  954. var k = Math.pow(10, prec);
  955. return '' + Math.floor(n * k) / k;
  956. };
  957. s = (prec ? toFixedFix(n, prec) : '' + Math.floor(n)).split('.');
  958. var re = /(-?\d+)(\d{3})/;
  959. // console.log(s)
  960. while (re.test(s[0])) {
  961. s[0] = s[0].replace(re, "$1" + sep + "$2");
  962. }
  963. if ((s[1] || '').length < prec) {
  964. s[1] = s[1] || '';
  965. s[1] += new Array(prec - s[1].length + 1).join('0');
  966. }
  967. return s.join(dec);
  968. },
  969. /**
  970. * 数值转字符串
  971. * @param {Number}
  972. * @return {String}
  973. */
  974. numStr(v) {
  975. return v.toString();
  976. },
  977. /**
  978. * 数值转字符串
  979. * @param {Number} num 当前数字
  980. * @param {Number} total 当前总数
  981. * @return {String} 返回百分比
  982. */
  983. numPer(num, total) {
  984. num = parseFloat(num);
  985. total = parseFloat(total);
  986. if (isNaN(num) || isNaN(total)) {
  987. return "-";
  988. }
  989. return total <= 0 ? "0%" : (Math.round(num / total * 10000) / 100.00) + "%";
  990. },
  991. /**
  992. * 取小数位
  993. * @param {String,Number}
  994. * @return {String}
  995. */
  996. numDigit(digit, num = 2) {
  997. return Number(digit).toFixed(num);
  998. },
  999. /**
  1000. * 取最小数
  1001. * @param {String,Number}
  1002. * @return {String}
  1003. */
  1004. numMin(v1, v2) {
  1005. return Math.min(Number(v1), Number(v2));
  1006. },
  1007. /**
  1008. * 取最大数
  1009. * @param {String,Number}
  1010. * @return {String}
  1011. */
  1012. numMax(v1, v2) {
  1013. return Math.max(Number(v1), Number(v2));
  1014. },
  1015. /**
  1016. * 返回数的绝对值
  1017. * @param {String,Number}
  1018. * @return {String}
  1019. */
  1020. numAbs(v) {
  1021. return Math.abs(Number(v));
  1022. },
  1023. /**
  1024. * 向上取整
  1025. * @param {String,Number}
  1026. * @return {String}
  1027. */
  1028. numUp(v) {
  1029. return Math.ceil(Number(v));
  1030. },
  1031. /**
  1032. * 向下取整
  1033. * @param {String,Number}
  1034. * @return {String}
  1035. */
  1036. numDown(v) {
  1037. return Math.floor(Number(v));
  1038. },
  1039. /**
  1040. * 去除小数部分
  1041. * @param {String,Number}
  1042. * @return {String}
  1043. */
  1044. numTrunc(v) {
  1045. return Math.trunc(Number(v));
  1046. },
  1047. /**
  1048. * 判断是否为正数/负数/零
  1049. * @param {String,Number}
  1050. * @return {String}
  1051. */
  1052. isSign(v) {
  1053. return Math.sign(Number(v));
  1054. },
  1055. /**
  1056. * 判断是否为整数
  1057. * @param {String,Number}
  1058. * @return {String}
  1059. */
  1060. isInt(v) {
  1061. return Number.isInteger(Number(v));
  1062. },
  1063. // 设置页面标题
  1064. title(title) {
  1065. wx.setNavigationBarTitle({
  1066. title
  1067. });
  1068. },
  1069. /**
  1070. * [URL参数拼接]
  1071. * @param [url,obj]
  1072. * @return {String}
  1073. */
  1074. createURL({
  1075. url,
  1076. obj
  1077. }) {
  1078. return new Promise((resolve, reject) => {
  1079. let props = "";
  1080. for (let p in obj) {
  1081. if (obj[p])
  1082. props += "&" + p + "=" + obj[p];
  1083. }
  1084. resolve(`${url}?${props.substr(1)}`);
  1085. });
  1086. },
  1087. /**
  1088. * 保留当前页面,跳转到应用内的某个页面
  1089. * @param {String} url 页面路径
  1090. * @param {Object} params 页面参数
  1091. */
  1092. navGo(url, params) {
  1093. this._openInterceptor('navigateTo', url, params);
  1094. },
  1095. /**
  1096. * 关闭当前页面,跳转到应用内的某个页面
  1097. * @param {String} url 页面路径
  1098. * @param {Object} params 页面参数
  1099. */
  1100. navTo(url, params) {
  1101. this._openInterceptor('redirectTo', url, params);
  1102. },
  1103. /**
  1104. * 跳转到 tabBar 页面,并关闭其他所有非 tabBar 页面
  1105. * @param {String} url 页面路径
  1106. * @param {Object} params 页面参数
  1107. */
  1108. navSwitch(url, params) {
  1109. this._openInterceptor('switchTab', url, params);
  1110. },
  1111. /**
  1112. * 关闭所有页面,打开到应用内的某个页面
  1113. * @param {String} url 页面路径
  1114. * @param {Object} params 页面参数
  1115. */
  1116. navRe(url, params) {
  1117. this._openInterceptor('reLaunch', url, params);
  1118. },
  1119. /**
  1120. * 返回页面
  1121. * @param {Number} delta 返回层级
  1122. * @param {None} params 无
  1123. */
  1124. navBack(delta = 1) {
  1125. wx.navigateBack({
  1126. delta
  1127. });
  1128. },
  1129. /**
  1130. * 页面跳转封装
  1131. * @param {String} method 微信JS方法
  1132. * @param {String} url 页面路径
  1133. * @param {Object} params 页面参数
  1134. */
  1135. _openInterceptor(method, url, params) {
  1136. if (this.IsPageNavigating) return;
  1137. this.IsPageNavigating = true;
  1138. params = this.param(params);
  1139. wx[method]({
  1140. url: url + params,
  1141. complete: () => {
  1142. this.IsPageNavigating = false;
  1143. }
  1144. });
  1145. },
  1146. // 授权数据解析
  1147. authParam(obj) {
  1148. if (obj) {
  1149. if (Object.keys(obj).length) {
  1150. return JSON.parse(obj);
  1151. }
  1152. } else {
  1153. return {};
  1154. }
  1155. },
  1156. /**
  1157. * 将对象解析成url字符串
  1158. * @param {Object} obj 参数对象
  1159. * @param {Boolean} unEncodeURI 不使用编码
  1160. * @return {String} 转换之后的url参数
  1161. */
  1162. param(obj = {}, unEncodeURI) {
  1163. let result = [];
  1164. for (let name of Object.keys(obj)) {
  1165. let value = obj[name];
  1166. result.push(name + '=' + (unEncodeURI ? value : encodeURIComponent(value)));
  1167. }
  1168. if (result.length) {
  1169. return '?' + result.join('&');
  1170. } else {
  1171. return '';
  1172. }
  1173. },
  1174. /**
  1175. * 将url字符串解析成对象
  1176. * @param {String} str 带url参数的地址
  1177. * @param {Boolean} unDecodeURI 不使用解码
  1178. * @return {Object} 转换之后的url参数
  1179. */
  1180. unparam(str = '', unDecodeURI) {
  1181. let result = {},
  1182. query = str.split('?')[1];
  1183. if (!query) return result;
  1184. let arr = query.split('&');
  1185. arr.forEach((item, idx) => {
  1186. let param = item.split('='),
  1187. name = param[0],
  1188. value = param[1] || '';
  1189. if (name) {
  1190. result[name] = unDecodeURI ? value : decodeURIComponent(value);
  1191. }
  1192. });
  1193. return result;
  1194. },
  1195. // 获取上级页面
  1196. getCurrentPageUrl() {
  1197. let pages = getCurrentPages();
  1198. let currentPage = pages[pages.length - 1];
  1199. let url = currentPage.route;
  1200. return url;
  1201. },
  1202. /**
  1203. * [微信小程序拦截]
  1204. * @param [url:地址,param:参数]
  1205. * @return {Null}
  1206. */
  1207. weChatAuth(url, param) {
  1208. let parse = JSON.stringify(encodeURIComponent(param));
  1209. if (!wx.getStorageSync('userInfo')) {
  1210. wx.navigateTo({
  1211. url: `/pages/auth/auth?url=${url}&parse=${parse}`
  1212. });
  1213. } else {
  1214. wx.navigateTo({
  1215. url: `${url}?${param}`
  1216. });
  1217. }
  1218. },
  1219. /**
  1220. * 获取当前页面路径
  1221. * @param {}
  1222. * @return {Object}
  1223. */
  1224. getCurrentPath() {
  1225. return this.getCurrentPage().__route__;
  1226. },
  1227. /**
  1228. * @param {Object} pay 支付参数
  1229. * @return {Callback} 无
  1230. * */
  1231. wePay(args, success, fail) {
  1232. wx.requestPayment({
  1233. "provider": args.provider || 'wxpay',
  1234. "timeStamp": args.timeStamp,
  1235. "nonceStr": args.nonceStr,
  1236. "package": args.package,
  1237. "signType": args.signType,
  1238. "paySign": args.paySign,
  1239. "success": (res) => {
  1240. success(JSON.stringify(res));
  1241. },
  1242. "fail": (err) => {
  1243. fail(JSON.stringify(err));
  1244. }
  1245. });
  1246. },
  1247. /**
  1248. * 校验手机号
  1249. * @param mobile
  1250. * @returns {boolean}
  1251. */
  1252. checkPhone(mobile) {
  1253. return /^[1][0-9]{10}$/.test(mobile)
  1254. },
  1255. /**
  1256. * 校验纯数字
  1257. * @param num
  1258. * @returns {boolean}
  1259. */
  1260. checkNum(num) {
  1261. return /^[0-9]+$/.test(num)
  1262. },
  1263. /**
  1264. * 校验用户名:1-20位字符,首字符为字母
  1265. * @param str
  1266. * @returns {RegExp}
  1267. */
  1268. checkUserName(str) {
  1269. return /^[a-zA-Z]{1,20}$/.test(str)
  1270. },
  1271. /**
  1272. * 校验密码:6-20位,数字、字母、下划线
  1273. * @param str
  1274. * @returns {boolean}
  1275. */
  1276. checkPwd(str) {
  1277. return /^(\\w){6,20}$/.test(str)
  1278. },
  1279. /**
  1280. * 校验正整数 + 0
  1281. * @param num
  1282. * @returns {boolean}
  1283. */
  1284. checkPositiveInteger(num) {
  1285. return /^[0-9]*[1-9][0-9]*$/.test(num)
  1286. },
  1287. /**
  1288. * 校验字符串是否为数字
  1289. * @param str
  1290. * @returns {boolean}
  1291. */
  1292. checkNumber(str) {
  1293. let regPos = /^\d+(\.\d+)?$/; //非负浮点数
  1294. let regNeg =
  1295. /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
  1296. if (regPos.test(str) || regNeg.test(str)) {
  1297. return true;
  1298. } else {
  1299. return false;
  1300. }
  1301. },
  1302. /**
  1303. * 校验字符串是否为电子邮箱
  1304. * @param str
  1305. * @returns {boolean}
  1306. */
  1307. checkEmail(str) {
  1308. return /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
  1309. .test(str);
  1310. },
  1311. /**
  1312. * 小于10补零
  1313. * @param {String,Number} number 传入的数值
  1314. * @return {String} 返回字符串
  1315. */
  1316. toDigit(any) {
  1317. return any.toString().replace(/^(\d)$/, `0$1`);
  1318. },
  1319. /**
  1320. * 类型判断
  1321. * @param {Any} value 任意需要判断的参数
  1322. * @return {String} 返回的类型
  1323. */
  1324. type(v) {
  1325. return Object.prototype.toString.call(v).split(' ')[1].substr(0, Object.prototype.toString.call(v)
  1326. .split(' ')[1].length -
  1327. 1);
  1328. },
  1329. /**
  1330. * 消息
  1331. * @param {String} key 设置key
  1332. * @return {NONE} 打印消息
  1333. */
  1334. toast(title = "提示", icon = "none", duration = "2") {
  1335. wx.showToast({
  1336. title,
  1337. icon,
  1338. duration: Number(duration) * 1e3
  1339. });
  1340. },
  1341. /**
  1342. * 取小数位
  1343. * @param {String,Number}
  1344. * @return {String}
  1345. */
  1346. digit(digit, num = 2) {
  1347. return Number(digit).toFixed(num);
  1348. },
  1349. /**
  1350. * 获取点击元素携带值
  1351. * @param {Object} e 点击对象
  1352. * @param {String} elename 点击所获取的具体值
  1353. * @return {Object,String} getElement 返回对象或者字符串
  1354. */
  1355. ele(e, elename) {
  1356. return elename ? e.currentTarget.dataset[elename] : e.currentTarget.dataset;
  1357. },
  1358. // 获取任意区间随机数
  1359. random(min, max) {
  1360. return min + Math.floor(Math.random() * (max - min + 1));
  1361. },
  1362. /**
  1363. * [匹配item是否在数组]
  1364. * @param [m:延迟时间]
  1365. * @return [none]
  1366. */
  1367. delay(m = 3, success) {
  1368. setTimeout(() => {
  1369. success()
  1370. }, m * 1e3);
  1371. },
  1372. /**
  1373. * [去除所有空格]
  1374. * @param [str:字符串]
  1375. * @return str
  1376. */
  1377. spaceRemove(str) {
  1378. return str.replace(/\s+/g, '');
  1379. },
  1380. /**
  1381. * [拨打号码]
  1382. * @param [phoneNumber:手机号]
  1383. * @return {Null}
  1384. */
  1385. phone(phoneNumber) {
  1386. wx.makePhoneCall({
  1387. phoneNumber: phoneNumber + ''
  1388. });
  1389. },
  1390. /**
  1391. * [底部适配(iphone XR\iphone X\ iphone Xs Max)]
  1392. * @return {Boolean}
  1393. */
  1394. isIphoneX() {
  1395. return new Promise((resolve, reject) => {
  1396. wx.getSystemInfo({
  1397. success(res) {
  1398. resolve(res.model.search('iPhone X') != -1);
  1399. },
  1400. fail(err) {
  1401. reject(err);
  1402. }
  1403. });
  1404. });
  1405. },
  1406. /**
  1407. * [sleep睡眠时间]
  1408. * @return {Boolean}
  1409. */
  1410. sleep(numberMillis) {
  1411. let now = new Date();
  1412. let exitTime = now.getTime() + numberMillis;
  1413. while (true) {
  1414. now = new Date();
  1415. if (now.getTime() > exitTime)
  1416. return;
  1417. }
  1418. },
  1419. /**
  1420. * @param {}
  1421. * @return {String} uuid 返回uuid
  1422. */
  1423. uuid() {
  1424. return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
  1425. (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
  1426. );
  1427. },
  1428. /**
  1429. * @param {Function}
  1430. * @return {String} time 返回程序所用时间
  1431. */
  1432. timeConsum(callback) {
  1433. console.time('timeTaken');
  1434. const r = callback();
  1435. console.timeEnd('timeTaken');
  1436. return r;
  1437. },
  1438. // 身份证号脱敏
  1439. desensitizationIdNumber(idNumber) {
  1440. return idNumber.replace(/^(.{6})(?:\d+)(.{4})$/, "\$1********\$2")
  1441. },
  1442. // 数据脱敏
  1443. desensitization(string = '', start, end) {
  1444. let star = ''
  1445. function makeStar(number) {
  1446. if (number > 0) {
  1447. star += '*';
  1448. return makeStar(--number)
  1449. } else {
  1450. return star
  1451. }
  1452. };
  1453. return string.substring(0, start) + makeStar(end - start) + string.substring(end)
  1454. },
  1455. // 手机号脱敏
  1456. desensitizationPhone(phone) {
  1457. return phone.substring(0, 3) + "****" + phone.substring(7)
  1458. }
  1459. }