1.日期事件格式化在tools文件内部(几分钟后的时间,格式化方式)

  1. // 1.日期事件格式化在tools文件内部(几分钟后的时间,格式化方式)
  2. export const lastformartTime = (time, rule = 'yyyy-mm-dd hh:mm:ss') => {
  3. let date = new Date();
  4. let min = date.getMinutes();
  5. date.setMinutes(min + time);
  6. let getYear = date.getFullYear().toString();
  7. let getMonth = (date.getMonth() + 1).toString().padStart(2, '0');
  8. let getDate = date.getDate().toString().padStart(2, '0');
  9. let getHours = date.getHours().toString().padStart(2, '0');
  10. let getMinutes = date.getMinutes().toString().padStart(2, '0');
  11. let getSeconds = date.getSeconds().toString().padStart(2, '0');
  12. if (rule == 'yyyy-mm-dd hh:mm:ss') {
  13. return `${getYear}-${getMonth}-${getDate} ${getHours}:${getMinutes}:${getSeconds}`
  14. } else if (rule == 'yyyy-mm-dd') {
  15. return `${getYear}-${getMonth}-${getDate}`
  16. }
  17. }
  18. // 使用
  19. import { lastformartTime } from "../../libs/tools";
  20. lastformartTime(5)

2.获取url参数

  1. // 2.获取url参数
  2. export const getUrlParams = () => {
  3. let url = decodeURI(window.location.hash);
  4. let urlParams = new Object();
  5. if (url.indexOf("?") != -1) {
  6. let str = url.substr(url.indexOf("?") + 1).split("&");
  7. for (let i = 0; i < str.length; i++) {
  8. urlParams[str[i].split("=")[0]] = unescape(str[i].split("=")[1]);
  9. }
  10. }
  11. return urlParams
  12. }

3.在js的prototype上定义方法

  1. // 1.手机号码格式化为344
  2. String.prototype.phoneFormat = function () {
  3. var str = this
  4. if (str.length == 0) {
  5. return str
  6. } else if ( str.length == 11) {
  7. str = str.substr(0, 3) + '-' + str.substr(3, 4) + '-' + str.substr(7, 4);
  8. }
  9. return str
  10. }
  11. // 使用时
  12. ('18336916987').phoneFormat()
  13. // 2.金额按照万分位格式化
  14. String.prototype.priceFormat = function () {
  15. var str = this
  16. return (str).replace(/(\d{1,4})(?=(\d{4})+(?:$|\.))/g,'$1,');
  17. }
  18. (price+'').priceFormat()
  1. // 取整, 使用按位运算符
  2. function toInt(num) {
  3. return num | 0
  4. }
  5. console.log(toInt(1.8)) // 1
  6. console.log(toInt(1.23232)) // 1
  7. // 取整 (位运算花样取整)
  8. ~~(-5.88) // -5
  9. // 判断奇偶
  10. return number & 1 === 1
  11. // 交换两个变量的值(不用第三个变量)
  12. let a = 1,
  13. b = 2;
  14. a = a ^ b;
  15. b = a ^ b; // 1
  16. a = a ^ b; // 2
  17. /**
  18. * 压缩图片
  19. * @param file 图片文件
  20. * @param callback 回调函数,压缩完要做的事,例如ajax请求等。
  21. */
  22. compressFile(file, callback) {
  23. let fileObj = file;
  24. let reader = new FileReader();
  25. reader.readAsDataURL(fileObj); //转base64
  26. reader.onload = function (e) {
  27. let image = new Image(); //新建一个img标签(还没嵌入DOM节点)
  28. image.src = e.target.result;
  29. image.onload = function () {
  30. let canvas = document.createElement("canvas"), // 新建canvas
  31. context = canvas.getContext("2d"),
  32. imageWidth = image.width / 4, //压缩后图片高度和宽度
  33. imageHeight = image.height / 5,
  34. data = "";
  35. canvas.width = imageWidth;
  36. canvas.height = imageHeight;
  37. context.drawImage(image, 0, 0, imageWidth, imageHeight);
  38. data = canvas.toDataURL("image/jpeg", 0.1); // 0.1压缩至以前的0.1倍
  39. let arr = data.split(","),
  40. mime = arr[0].match(/:(.*?);/)[1], // 转成blob
  41. bstr = atob(arr[1]),
  42. n = bstr.length,
  43. u8arr = new Uint8Array(n);
  44. while (n--) {
  45. u8arr[n] = bstr.charCodeAt(n);
  46. }
  47. let files = new window.File(
  48. [new Blob([u8arr], { type: mime })],
  49. "test.jpeg",
  50. { type: "image/jpeg" }
  51. ); // 转成file
  52. callback(files); // 回调
  53. };
  54. };
  55. },
  56. /**
  57. * dataURL转file
  58. * @param {*} dataUrl
  59. * @param {String} filename 文件名
  60. * @param {String} filetype 文件类型
  61. */
  62. export const dataURLtoFile = (dataUrl, filename, filetype = 'image/jpeg') => {
  63. // 获取到base64编码
  64. const arr = dataUrl.split(',');
  65. // 将base64编码转为字符串
  66. const bstr = window.atob(arr[1]);
  67. let n = bstr.length;
  68. const u8arr = new Uint8Array(n); // 创建初始化为0的,包含length个元素的无符号整型数组
  69. while (n--) {
  70. u8arr[n] = bstr.charCodeAt(n);
  71. }
  72. return new File([u8arr], filename, {
  73. type: filetype,
  74. });
  75. };
  76. /**
  77. * 拷贝数据
  78. * @param {}
  79. */
  80. // 定义一个深拷贝函数 接收目标target参数
  81. export function deepClone(target) {
  82. // 定义一个变量
  83. let result;
  84. // 如果当前需要深拷贝的是一个对象的话
  85. if (typeof target === 'object') {
  86. // 如果是一个数组的话
  87. if (Array.isArray(target)) {
  88. result = []; // 将result赋值为一个数组,并且执行遍历
  89. for (let i in target) {
  90. // 递归克隆数组中的每一项
  91. result.push(deepClone(target[i]))
  92. }
  93. // 判断如果当前的值是null的话;直接赋值为null
  94. } else if (target === null) {
  95. result = null;
  96. // 判断如果当前的值是一个RegExp对象的话,直接赋值
  97. } else if (target.constructor === RegExp) {
  98. result = target;
  99. } else {
  100. // 否则是普通对象,直接for in循环,递归赋值对象的所有值
  101. result = {};
  102. for (let i in target) {
  103. result[i] = deepClone(target[i]);
  104. }
  105. }
  106. // 如果不是对象的话,就是基本数据类型,那么直接赋值
  107. } else {
  108. result = target;
  109. }
  110. // 返回最终结果
  111. return result;
  112. }
  113. /**
  114. *
  115. * @param {Bold} img 图片流
  116. * @param {Function} callback 回调
  117. */
  118. export function getBase64(img, callback) {
  119. const reader = new FileReader();
  120. reader.addEventListener('load', () => callback(reader.result));
  121. reader.readAsDataURL(img);
  122. }
  123. /**
  124. * oss上传图片时转化为buffer
  125. * @param {bold} img 图片流
  126. * @returns {OSSBuffer} buffer对象
  127. */
  128. export function readFileAsBuffer(file) {
  129. const reader = new FileReader();
  130. return new Promise((resolve) => {
  131. reader.readAsDataURL(file);
  132. reader.onload = function () {
  133. const base64File = reader.result.replace(
  134. /^data:\w+\/\w+;base64,/,
  135. ""
  136. );
  137. resolve(new OSS.Buffer(base64File, "base64"));
  138. };
  139. });
  140. }/**
  141. * 创建一个带有过期时间的session
  142. * @param {String} key 设置localstorage的key
  143. * @param {String} value 设置localstorage的value
  144. */
  145. export function setSession(key, value) {
  146. const curTime = Date.now();
  147. localStorage.setItem(key, JSON.stringify({ data: value, time: curTime }));
  148. }
  149. // 判断值是否为空
  150. export function isEmpty(type) {
  151. return [null, undefined, ""].includes(type);
  152. };
  153. /**
  154. * 函数节流
  155. * @param {Function} fn 执行函数
  156. * @param {Number} ms //倒计时时间
  157. */
  158. export function debounce(fn, ms = 500) {
  159. let timeoutId
  160. return function () {
  161. clearTimeout(timeoutId)
  162. timeoutId = setTimeout(() => {
  163. fn.apply(this, arguments)
  164. }, ms)
  165. }
  166. }
  167. /**
  168. * 根据key和过期时间获取session
  169. * @param {String} key 获取localstorage的key
  170. * @param {Number} exp localstorage 的过期时间
  171. * return {String} localstorage key 对应的值
  172. */
  173. export function getSession(key, exp) {
  174. const data = localStorage.getItem(key);
  175. if (!data) {
  176. return '';
  177. }
  178. const dataObj = JSON.parse(data);
  179. if (!isEmpty(exp) && new Date().getTime() - dataObj.time > exp) {
  180. return '';
  181. }
  182. return dataObj.data;
  183. }
  184. /**
  185. * 删除一个session
  186. * @param {String} key
  187. */
  188. export function destroySession(key) {
  189. localStorage.removeItem(key);
  190. }

4.判断数据类型

  1. const isType = type => target => `[object ${type}]` === Object.prototype.toString.call(target)
  2. const isString = isType('String')
  3. const isNumber = isType('Number')
  4. const isSymbol = isType('Symbol')
  5. const isUndefined = isType('Undefined')
  6. const isNull = isType('Null')
  7. const isFunction = isType('Function')
  8. const isDate = isType('Date')
  9. const isArray = isType('Array')
  10. const isRegExp = isType('RegExp')
  11. const isError = isType('Error')
  12. const isHTMLDocument = isType('HTMLDocument')
  13. const isglobal = isType('global')