index.js 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. /**
  2. * 检测类型
  3. * @param target 检测的目标
  4. */
  5. export function checkType(target) {
  6. const value = Object.prototype.toString.call(target);
  7. const result = value.match(/\[object (\S*)\]/)[1];
  8. return result.toLocaleLowerCase();
  9. }
  10. /**
  11. * 判断任意值的类型,作用与`checkType`一致,外加一个辅助功能:当函数返回值为`true`时,可以传入泛型来确定`target`的类型(类型收窄)
  12. * @param target 判断目标
  13. * @param type 判断的类型
  14. */
  15. export function isType(target, type) {
  16. return checkType(target) === type;
  17. }
  18. /**
  19. * 修改属性值-只修改之前存在的值
  20. * @param target 修改的目标
  21. * @param value 修改的内容
  22. */
  23. export function modifyData(target, value) {
  24. for (const key in value) {
  25. if (Object.prototype.hasOwnProperty.call(target, key)) {
  26. const item = value[key];
  27. const _target = target[key];
  28. // 深层逐个赋值
  29. if (isType(_target, "object")) {
  30. modifyData(_target, item);
  31. }
  32. else {
  33. target[key] = item;
  34. }
  35. }
  36. }
  37. }
  38. /**
  39. * 设置属性值-之前不存在的值也根据传入的`value`值去设置
  40. * @param target 设置的目标
  41. * @param value 设置的内容
  42. */
  43. export function setData(target, value) {
  44. for (const key in value) {
  45. target[key] = value[key];
  46. }
  47. }
  48. /**
  49. * 格式化日期
  50. * @param value 指定日期
  51. * @param format 格式化的规则
  52. * @example
  53. * ```js
  54. * formatDate();
  55. * formatDate(1603264465956);
  56. * formatDate(1603264465956, "h:m:s");
  57. * formatDate(1603264465956, "Y年M月D日");
  58. * ```
  59. */
  60. export function formatDate(value = Date.now(), format = "Y-M-D h:m:s") {
  61. if (["null", null, "undefined", undefined, ""].includes(value))
  62. return "";
  63. // ios 和 mac 系统中,带横杆的字符串日期是格式不了的,这里做一下判断处理
  64. if (typeof value === "string" && new Date(value).toString() === "Invalid Date") {
  65. value = value.replace(/-/g, "/");
  66. }
  67. const formatNumber = (n) => `0${n}`.slice(-2);
  68. const date = new Date(value);
  69. const formatList = ["Y", "M", "D", "h", "m", "s"];
  70. const resultList = [];
  71. resultList.push(date.getFullYear().toString());
  72. resultList.push(formatNumber(date.getMonth() + 1));
  73. resultList.push(formatNumber(date.getDate()));
  74. resultList.push(formatNumber(date.getHours()));
  75. resultList.push(formatNumber(date.getMinutes()));
  76. resultList.push(formatNumber(date.getSeconds()));
  77. for (let i = 0; i < resultList.length; i++) {
  78. format = format.replace(formatList[i], resultList[i]);
  79. }
  80. return format;
  81. }
  82. /**
  83. * 点击复制
  84. * @param text 复制的内容
  85. * @param success 成功回调
  86. * @param fail 出错回调
  87. */
  88. export function copyText(text, success, fail) {
  89. text = text.replace(/(^\s*)|(\s*$)/g, "");
  90. if (!text) {
  91. fail && fail("复制的内容不能为空!");
  92. return;
  93. }
  94. const id = "the-clipboard";
  95. let clipboard = document.getElementById(id);
  96. if (!clipboard) {
  97. clipboard = document.createElement("textarea");
  98. clipboard.id = id;
  99. clipboard.readOnly = true;
  100. clipboard.style.cssText = "font-size: 15px; position: fixed; top: -1000%; left: -1000%;";
  101. document.body.appendChild(clipboard);
  102. }
  103. clipboard.value = text;
  104. clipboard.select();
  105. clipboard.setSelectionRange(0, clipboard.value.length);
  106. const state = document.execCommand("copy");
  107. if (state) {
  108. success && success();
  109. }
  110. else {
  111. fail && fail("复制失败");
  112. }
  113. }
  114. /**
  115. * 输入只能是数字
  116. * @param value
  117. * @param decimal 是否要保留小数
  118. * @param negative 是否可以为负数
  119. */
  120. export function inputOnlyNumber(value, decimal, negative) {
  121. let result = value.toString().trim();
  122. if (result.length === 0)
  123. return "";
  124. const minus = (negative && result[0] == "-") ? "-" : "";
  125. if (decimal) {
  126. result = result.replace(/[^0-9.]+/ig, "");
  127. let array = result.split(".");
  128. if (array.length > 1) {
  129. result = array[0] + "." + array[1];
  130. }
  131. }
  132. else {
  133. result = result.replace(/[^0-9]+/ig, "");
  134. }
  135. return minus + result;
  136. }
  137. /**
  138. * ES5 兼容 ES6 `Array.findIndex`
  139. * @param array
  140. * @param compare 对比函数
  141. */
  142. export function findIndex(array, compare) {
  143. var result = -1;
  144. for (var i = 0; i < array.length; i++) {
  145. if (compare(array[i], i)) {
  146. result = i;
  147. break;
  148. }
  149. }
  150. return result;
  151. }
  152. /**
  153. * 自定义对象数组去重
  154. * @param array
  155. * @param compare 对比函数
  156. * @example
  157. * ```js
  158. * const list = [{ id: 10, code: "abc" }, {id: 12, code: "abc"}, {id: 12, code: "abc"}];
  159. * filterRepeat(list, (a, b) => a.id == b.id)
  160. * ```
  161. */
  162. export function filterRepeat(array, compare) {
  163. return array.filter((element, index, self) => {
  164. return findIndex(self, el => compare(el, element)) === index;
  165. });
  166. }
  167. /**
  168. * 判断是否外部链接
  169. * @param path 路径
  170. */
  171. export function isExternal(path) {
  172. return /^(https?:|mailto:|tel:)/.test(path);
  173. }
  174. /**
  175. * `JSON`转`FormData`
  176. * @param params `JSON`对象
  177. * @example
  178. * ```js
  179. * const info = { name: "hjs", id: 123 };
  180. * const val = jsonToFormData(info);
  181. * console.log(val); // "name=hjs&id=123"
  182. * ```
  183. */
  184. export function jsonToFormData(params) {
  185. let result = "";
  186. for (const key in params) {
  187. result += `&${key}=${params[key]}`;
  188. }
  189. return result.slice(1);
  190. }
  191. /**
  192. * `JSON`格式化对象,内置错误捕捉处理,错误时返回默认值
  193. * - 默认返回空对象: `{}`
  194. * @param target 要格式化的目标对象
  195. * @param defaultValue 默认返回值
  196. */
  197. export function jsonParse(target, defaultValue = {}) {
  198. let result = defaultValue;
  199. if (isType(target, "string")) {
  200. try {
  201. result = JSON.parse(target);
  202. }
  203. catch (error) {
  204. console.warn("JSON格式化对象错误 >>", error);
  205. }
  206. }
  207. return result;
  208. }
  209. /** 检查是否移动端 */
  210. export function isMobile() {
  211. const pattern = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|OperaMini/i;
  212. return pattern.test(navigator.userAgent);
  213. }