WhiteSevsUtils

一个好用的工具类

当前为 2022-11-27 提交的版本,查看 最新版本

此脚本不应直接安装。它是供其他脚本使用的外部库,要使用该库请加入元指令 // @require https://update.gf.qytechs.cn/scripts/455186/1121656/WhiteSevsUtils.js

  1. /*
  2. * @overview 自己常用的工具类定义
  3. * @copyright GPL-3.0-only
  4. * @author WhiteSevs
  5. * @version 0.1
  6. */
  7. let Utils = {};
  8.  
  9. /*
  10. * @param {string|function} func - 需要捕获错误的函数或函数格式的字符串
  11. * @param {object} params - 该函数的参数和捕获到错误的函数的参数,类型为数组Array
  12. * @param {string|function} errorFunc - 捕获到错误后执行的函数或函数格式的字符串
  13. * @example Utils.tryCatch("(pam)=>{console.log('this is a function and params is' + pam[0])}",["参数1"],"()=>{console.log('对错误进行处理判断')}");
  14. */
  15. Utils.tryCatch = (func, params, errorFunc) => {
  16. /* 捕获错误 */
  17. if(func == null){
  18. throw "警告: 参数 func 为不存在"
  19. }
  20. if (typeof func !== "function" && typeof func !== "string" ) {
  21. throw "参数 func 类型必须为function类型或者string类型"
  22. }
  23. if (params != null && typeof params !== "object" && typeof params !== "string") {
  24. throw "参数 params 类型必须为object类型或者string类型"
  25. }
  26. if (errorFunc != null && typeof errorFunc !== "object" && typeof errorFunc !== "string") {
  27. throw "参数 errorFunc 类型必须为function类型或者string类型"
  28. }
  29. var result = null;
  30. try {
  31. result = typeof func === "string" ? window.eval(func) : func(params);
  32. } catch (error) {
  33. console.log("%c" + (func.name ? func.name : func + "出现错误"), "color: #f20000");
  34. console.log("%c" + ("错误原因:" + error), "color: #f20000");
  35. console.trace(func);
  36. result = typeof func === "string" ? window.eval(errorFunc) : errorFunc(params);
  37. } finally {
  38. return result;
  39. }
  40. };
  41.  
  42. /*
  43. * @description 格式化时间字符串
  44. * @param {string} str - 字符串格式的时间,例如:2022-11-21 00:00:00,或者是 00:00:00
  45. * @return {number} - 返回时间戳
  46. * @example Utils.formatTextToTimeStamp("2022-11-21 00:00:00");
  47. */
  48. Utils.formatTextToTimeStamp = (text) => {
  49. /* 把字符串格式的时间(完整,包括日期和时间)格式化成时间戳 */
  50. if (typeof text !== 'string') {
  51. throw "参数 text 必须为string类型";
  52. };
  53. if (text.length === 8) {
  54. /* 参数只有时间 */
  55. var today = new Date();
  56. text = today.getFullYear() + "-" + (today.getMonth() + 1) + "-" + today.getDate() + " " + text;
  57. };
  58. text = text.substring(0, 19);
  59. text = text.replace(/-/g, '/');
  60. var timestamp = new Date(text).getTime();
  61. return timestamp;
  62. };
  63.  
  64. /*
  65. * @description 定位网页中字符串位置并标亮,注意,该字符串必须是能在网页中看得到的,隐藏的是无法定位的
  66. * @param {string} str - 需要寻找的字符串
  67. * @param {boolean} caseSensitive - 区分大小写
  68. * @return {boolean} true/false - 找到为true,否则false
  69. * @example Utils.findWindowPageString("xxxxx");
  70. * @exampleResult true
  71. */
  72.  
  73. Utils.findWindowPageString = (str,caseSensitive=false) => {
  74. var TRange = null;
  75. var strFound;
  76. if (window.find) {
  77. // CODE FOR BROWSERS THAT SUPPORT window.find
  78. strFound = self.find(str,caseSensitive,true,true,false);
  79. if (strFound && self.getSelection && !self.getSelection().anchorNode) {
  80. strFound = self.find(str,caseSensitive,true,true,false)
  81. }
  82. if (!strFound) {
  83. strFound = self.find(str, 0, 1)
  84. while (self.find(str, 0, 1))
  85. continue
  86. }
  87. } else if (navigator.appName.indexOf("Microsoft") != -1) {
  88. // EXPLORER-SPECIFIC CODE
  89. if (TRange != null) {
  90. TRange.collapse(false)
  91. strFound = TRange.findText(str)
  92. if (strFound)
  93. TRange.select()
  94. }
  95. if (TRange == null || strFound == 0) {
  96. TRange = self.document.body.createTextRange()
  97. strFound = TRange.findText(str)
  98. if (strFound)
  99. TRange.select()
  100. }
  101. } else if (navigator.appName == "Opera") {
  102. alert("Opera browsers not supported, sorry...")
  103. return;
  104. };
  105. return strFound ? true:false;
  106. }
  107.  
  108. /*
  109. * @description 格式化byte为KB、MB、GB、TB、PB、EB、ZB、YB、BB、NB、DB
  110. * @param {number} bitSize - 字节
  111. * @param {boolean} addType - 是否添加单位,默认添加
  112. * @return {string|number} - 添加单位就是字符串,否则为float类型,保留两位
  113. * @example Utils.formatByteToSize("812304");
  114. * @exampleResult
  115. */
  116. Utils.formatByteToSize = (byteSize, addType = true) => { // B字节转KB、MB、GB
  117. byteSize = parseInt(byteSize);
  118. if (isNaN(byteSize)) {
  119. throw "参数 byteSize 格式不正确";
  120. }
  121. var result = 0;
  122. var resultType = "KB";
  123. var sizeData = {};
  124. sizeData.KB = 1024;
  125. sizeData.MB = sizeData.KB * sizeData.KB;
  126. sizeData.GB = sizeData.MB * sizeData.KB;
  127. sizeData.TB = sizeData.GB * sizeData.KB;
  128. sizeData.PB = sizeData.TB * sizeData.KB;
  129. sizeData.EB = sizeData.PB * sizeData.KB;
  130. sizeData.ZB = sizeData.EB * sizeData.KB;
  131. sizeData.YB = sizeData.ZB * sizeData.KB;
  132. sizeData.BB = sizeData.YB * sizeData.KB;
  133. sizeData.NB = sizeData.BB * sizeData.KB;
  134. sizeData.DB = sizeData.NB * sizeData.KB;
  135. for (key in sizeData) {
  136. result = byteSize / sizeData[key];
  137. resultType = key;
  138. if (sizeData.KB >= result) {
  139. break;
  140. }
  141. };
  142. result = result.toFixed(2);
  143. result = addType ? result + resultType.toString() : parseFloat(result);
  144. return result;
  145. }
  146.  
  147. /*
  148. * @description 数组按照内部某个值的大小比对排序,如[{"time":"2022-1-1"},{"time":"2022-2-2"}]
  149. * @param {string} propertyName - 数组内部项的某个属性的名称
  150. * @param {boolean} sortByDesc - 排序方式为倒序,值为true或false,默认为true
  151. * @return {object} - 返回比较排序完成的数组
  152. * @example [{"time":"2022-1-1"},{"time":"2022-2-2"}].sort(Utils.sortListByProperty("time"))
  153. * @example [{"time":"2022-1-1"},{"time":"2022-2-2"}].sort(Utils.sortListByProperty("time",false))
  154. */
  155. Utils.sortListByProperty = (propertyName, sortByDesc = true) => {
  156. if (typeof sortByDesc !== 'boolean') {
  157. throw "参数 sortByDesc 必须为boolean类型";
  158. };
  159. return function (after_obj, before_obj) {
  160. var beforeValue = before_obj[propertyName]; /* 前 */
  161. var aferValue = after_obj[propertyName]; /* 后 */
  162. if (sortByDesc) {
  163. if (aferValue > beforeValue) {
  164. return -1
  165. } else if (aferValue < beforeValue) {
  166. return 1
  167. } else {
  168. return 0
  169. }
  170. } else {
  171. if (aferValue < beforeValue) {
  172. return -1
  173. } else if (aferValue > beforeValue) {
  174. return 1
  175. } else {
  176. return 0
  177. }
  178. }
  179. }
  180. };
  181.  
  182. /*
  183. * @description Array添加一个内部属性,数组根据相同的字段合并成字符串
  184. * @example [{"name":"Array内部方法: "},{"name":"mergeToString"}].mergeToString("name");
  185. */
  186. Utils.mergeArrayToString = (list,propertyName) => {
  187. if(list == null){
  188. throw "参数 list 不能为空";
  189. }
  190. if (propertyName == null) {
  191. throw "参数 propertyName 不能为null";
  192. }
  193. var content = "";
  194. Array.from(list).forEach((item) => {
  195. content = content + item[propertyName];
  196. })
  197. return content;
  198. };
  199.  
  200. /*
  201. * @description JSON内所有的值转为Array数组
  202. * @param {object} _json_ - JSON数据
  203. * @return {object} - 返回数组
  204. * @example Utils.jsonAllValueToArray({"Utils":"jsonToArray","return","Array"});
  205. * @exampleResult ['jsonToArray', 'Array']
  206. */
  207. Utils.jsonAllValueToArray = (_json_) => {
  208. if (typeof _json_ !== 'object') {
  209. throw "参数 _json_ 必须为object类型"
  210. }
  211. var retArray = [];
  212. Object.keys(_json_).forEach(function (key) {
  213. retArray = retArray.concat(_json_[key]);
  214. })
  215. return retArray;
  216. };
  217.  
  218. /*
  219. * @description JSON格式的字符串转为JSON对象
  220. * @param {string} text - JSON格式的字符串
  221. * @return {object} - 返回JSON对象
  222. * @example Utils.jsonStrToObject('{"Utils":"jsonStrToObject","return","json"}');
  223. * @exampleResult {"Utils":"jsonStrToObject","return","json"}
  224. */
  225. Utils.jsonStrToObject = (text) => {
  226. if (typeof text !== 'string') {
  227. throw "参数 text 类型必须为string类型"
  228. }
  229. return window.eval("(" + text + ")");
  230. };
  231.  
  232. /*
  233. * @description 获取数组的随机值
  234. * @param {string} array - 数组数据
  235. * @return {string} - 返回数组的随机值
  236. * @example Utils.getArrayRandValue(["Utils","getArrayRandValue"]);
  237. * @exampleResult getArrayRandValue
  238. */
  239. Utils.getArrayRandValue = (_array_) => {
  240. return _array_[Math.floor(Math.random() * _array_.length)];
  241. };
  242.  
  243. /*
  244. * @description 获取两个数字区间的随机值
  245. * @param {number} number - 数字区间
  246. * @param {number} number2 - 数字区间
  247. * @return {number} - 返回两个数字区间的随机值
  248. * @example Utils.getRandNumber(1,10);
  249. * @exampleResult 5
  250. * @example Utils.getRandNumber(10,1);
  251. * @exampleResult 8
  252. */
  253. Utils.getRandNumber = (number, number2) => {
  254. if (typeof number !== "number") {
  255. throw "参数 number 必须为number类型";
  256. }
  257. if (typeof number2 !== "number") {
  258. throw "参数 number2 必须为number类型";
  259. }
  260. var leftNumber = number > number2 ? number2 : number;
  261. var rightNumber = number > number2 ? number : number2;
  262. return Math.round(Math.random() * (rightNumber - leftNumber)) + leftNumber;
  263. };
  264.  
  265. /*
  266. * @description 获取格式化后的Date类型时间
  267. * @param {string} text - 需要格式化的字符串或者时间戳
  268. * @param {string} types - 格式化成的显示类型
  269. * yyyy 年
  270. * MM 月
  271. * dd 天
  272. * HH 时 (24小时制)
  273. * hh 时 (12小时制)
  274. * mm 分
  275. * ss 秒
  276. * @return {string} - 返回格式化后的时间
  277. * @example Utils.getFormatTime("HH:mm:ss","2022-08-21 23:59:00");
  278. * @exampleResult 23:59:00
  279. * @example Utils.getFormatTime("HH:mm:ss",1669187424988);
  280. * @exampleResult 15:10:13
  281. */
  282. Utils.getFormatTime = (types = "yyyy-MM-dd HH:mm:ss", text) => {
  283. if( typeof types !== "string"){
  284. throw "参数 types 必须是string类型";
  285. }
  286. if(text != null && (typeof text !== "string" && typeof text !== "number") ){
  287. throw "参数 text 必须是string类型或者number类型";
  288. }
  289. var time = text == null ? new Date(): new Date(text);
  290. function _checkTime_(i) {
  291. /* 校验时间补0 */
  292. if (i < 10) return "0" + i;
  293. return i;
  294. }
  295.  
  296. function _timeSystemChange_(_hour_) {
  297. /* 时间制修改 24小时制转12小时制 */
  298. return _hour_ > 12 ? _hour_ - 12 : _hour_;
  299. };
  300. var timeRegexp = {
  301. "yyyy": time.getFullYear(),
  302. /* 年 */
  303. "MM": _checkTime_(time.getMonth() + 1),
  304. /* 月 */
  305. "dd": _checkTime_(time.getDate()),
  306. /* 日 */
  307. "HH": _checkTime_(time.getHours()),
  308. /* 时 (24小时制) */
  309. "hh": _checkTime_(_timeSystemChange_(time.getHours())),
  310. /* 时 (12小时制) */
  311. "mm": _checkTime_(time.getMinutes()),
  312. /* 分 */
  313. "ss": _checkTime_(time.getSeconds()),
  314. /* 秒 */
  315. };
  316. Object.keys(timeRegexp).forEach(function (key) {
  317. var replaecRegexp = new RegExp(key, "g");
  318. types = types.replace(replaecRegexp, timeRegexp[key]);
  319. });
  320. return types;
  321. },
  322.  
  323. /*
  324. * @description 【手机】检测点击的地方是否在该元素区域内
  325. * @param {object} obj - 需要检测的DOM元素
  326. * @return {boolean} - 返回true或false
  327. * @example Utils.checkClickInDOM(document.querySelector(".xxx"));
  328. * @exampleResult false
  329. */
  330. Utils.checkClickInDOM = (obj) => {
  331. if (typeof obj !== "object") {
  332. throw "参数 obj 类型必须为object类型";
  333. }
  334. var x = Number(window.event.clientX) /* 鼠标相对屏幕横坐标 */
  335. var y = Number(window.event.clientY) /* 鼠标相对屏幕纵坐标 */
  336.  
  337. var obj_x_left = Number(obj.getBoundingClientRect().left) /* obj相对屏幕的横坐标 */
  338. var obj_x_right = Number(
  339. obj.getBoundingClientRect().left + obj.clientWidth
  340. ) /* obj相对屏幕的横坐标+width */
  341.  
  342.  
  343. var obj_y_bottom = Number(
  344. obj.getBoundingClientRect().top + obj.clientHeight
  345. ) /* obj相对屏幕的纵坐标+height */
  346. var obj_y_top = Number(obj.getBoundingClientRect().top) /* obj相对屏幕的纵坐标 */
  347. if ((x >= obj_x_left && x <= obj_x_right && y >= obj_y_top && y <= obj_y_bottom) || obj.outerHTML.indexOf(window.event.target.innerHTML) != -1) {
  348. return true
  349. } else {
  350. return false
  351. }
  352. };
  353.  
  354. /*
  355. * @description 同步执行延时函数
  356. * @param {object|string} fnStr - 需要延时的函数或字符串格式的函数
  357. * @param {number} delayTime - 需要检测的DOM元素
  358. * @return {All|无返回值} - 返回自定义类型数据或者无返回
  359. * @example await Utils.asyncSetTimeOut(xxxFunction, 2500);
  360. * @exampleResult xxx
  361. * @example await Utils.asyncSetTimeOut("()=>{console.log(12345)}", 2500);
  362. * @exampleResult 无返回值
  363. */
  364. Utils.asyncSetTimeOut = (fnStr, delayTime) => {
  365. if (typeof fnStr !== "function" && typeof fnStr !== "string") {
  366. throw "参数 fnStr 类型必须为function类型或者string类型"
  367. };
  368. if (typeof delayTime !== "number") {
  369. throw "参数 delayTime 类型必须为number类型"
  370. };
  371. return new Promise(res => {
  372. setTimeout(() => {
  373. res(Utils.tryCatch(fnStr));
  374. }, delayTime);
  375. })
  376. };
  377.  
  378. /*
  379. * @description 同步执行foreach函数,遍历数组
  380. * @param {object} arrayData - 需要遍历的数组
  381. * @param {function} handleDataFunction - 对该数组进行操作的函数,该函数的参数为数组格式的参数,[数组下标,数组项]
  382. * @return 无返回值
  383. * @example await Utils.asyncArrayForEach([1,2,3],xxxFunction);
  384. */
  385. Utils.asyncArrayForEach = (arrayData, handleDataFunction) => {
  386. if (typeof arrayData !== "object") {
  387. throw "参数 arrayData 类型必须为object类型"
  388. }
  389. if (typeof handleDataFunction !== "object" && typeof handleDataFunction !== "string") {
  390. throw "参数 handleDataFunction 类型必须为object或者string类型"
  391. }
  392. return Promise.all(
  393. Array.from(arrayData).map(async (item, index) => {
  394. await Utils.tryCatch(handleDataFunction, [index, item]);
  395. })
  396. );
  397. };
  398.  
  399. /*
  400. * @description 同步延迟xxx毫秒
  401. * @param {number} delayTime - 需要遍历的数组
  402. * @return {无返回值}
  403. * @example await Utils.sleep(2500); - 同步延时2500毫秒
  404. */
  405. Utils.sleep = (delayTime) => {
  406. if (typeof delayTime !== "number") {
  407. throw "参数 delayTime 类型必须为number类型"
  408. }
  409. return new Promise(res => {
  410. setTimeout(() => {
  411. res();
  412. }, delayTime);
  413. })
  414. };
  415.  
  416. /*
  417. * @description 注册(不可用)全局函数Cookies
  418. * @function Cookies.get("key")
  419. * @param {string|number} key - 需要获取的cookie的key
  420. * @return {string} 获取到的cookie值或者为空
  421. * @function Cookies.set("key","value",8400);
  422. * @param {string|number} key - 需要设置的cookie的key
  423. * @param {All} key - 需要设置的cookie的value
  424. * @param {number} time - 需要设置的cookie的过期时间
  425. * @return 无返回值
  426. * @example Utils.registerWindowCookies();
  427. * Cookies.get("xxxx");
  428. */
  429. Utils.registerWindowCookies = () => {
  430. /*! js-cookie v3.0.1 | MIT */
  431. (function (global, factory) {
  432. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  433. typeof define === 'function' && define.amd ? define(factory) :
  434. (global = global || self, (function () {
  435. var current = global.Cookies;
  436. var exports = global.Cookies = factory();
  437. exports.noConflict = function () {
  438. global.Cookies = current;
  439. return exports;
  440. };
  441. }()));
  442. }(this, (function () {
  443. 'use strict';
  444. /* eslint-disable no-var */
  445. function assign(target) {
  446. for (var i = 1; i < arguments.length; i++) {
  447. var source = arguments[i];
  448. for (var key in source) {
  449. target[key] = source[key];
  450. }
  451. }
  452. return target
  453. }
  454. /* eslint-enable no-var */
  455. /* eslint-disable no-var */
  456. var defaultConverter = {
  457. read: function (value) {
  458. if (value[0] === '"') {
  459. value = value.slice(1, -1);
  460. }
  461. return value.replace(/(%[\dA-F]{2})+/gi, decodeURIComponent)
  462. },
  463. write: function (value) {
  464. return encodeURIComponent(value).replace(
  465. /%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,
  466. decodeURIComponent
  467. )
  468. }
  469. };
  470. /* eslint-enable no-var */
  471.  
  472. /* eslint-disable no-var */
  473.  
  474. function init(converter, defaultAttributes) {
  475. function set(key, value, attributes) {
  476. if (typeof document === 'undefined') {
  477. return
  478. }
  479.  
  480. attributes = assign({}, defaultAttributes, attributes);
  481.  
  482. if (typeof attributes.expires === 'number') {
  483. attributes.expires = new Date(Date.now() + attributes.expires * 864e5);
  484. }
  485. if (attributes.expires) {
  486. attributes.expires = attributes.expires.toUTCString();
  487. }
  488.  
  489. key = encodeURIComponent(key)
  490. .replace(/%(2[346B]|5E|60|7C)/g, decodeURIComponent)
  491. .replace(/[()]/g, escape);
  492.  
  493. var stringifiedAttributes = '';
  494. for (var attributeName in attributes) {
  495. if (!attributes[attributeName]) {
  496. continue
  497. }
  498.  
  499. stringifiedAttributes += '; ' + attributeName;
  500.  
  501. if (attributes[attributeName] === true) {
  502. continue
  503. }
  504. /* Considers RFC 6265 section 5.2:
  505. ...
  506. 3. If the remaining unparsed-attributes contains a %x3B (";")
  507. character:
  508. Consume the characters of the unparsed-attributes up to,
  509. not including, the first %x3B (";") character.
  510. ... */
  511. stringifiedAttributes += '=' + attributes[attributeName].split(';')[0];
  512. }
  513.  
  514. return (document.cookie =
  515. key + '=' + converter.write(value, key) + stringifiedAttributes)
  516. }
  517.  
  518. function get(key) {
  519. if (typeof document === 'undefined' || (arguments.length && !key)) {
  520. return
  521. }
  522.  
  523. /* To prevent the for loop in the first place assign an empty array
  524. in case there are no cookies at all. */
  525. var cookies = document.cookie ? document.cookie.split('; ') : [];
  526. var jar = {};
  527. for (var i = 0; i < cookies.length; i++) {
  528. var parts = cookies[i].split('=');
  529. var value = parts.slice(1).join('=');
  530.  
  531. try {
  532. var foundKey = decodeURIComponent(parts[0]);
  533. jar[foundKey] = converter.read(value, foundKey);
  534.  
  535. if (key === foundKey) {
  536. break
  537. }
  538. } catch (e) {}
  539. }
  540.  
  541. return key ? jar[key] : jar
  542. }
  543.  
  544. return Object.create({
  545. set: set,
  546. get: get,
  547. remove: function (key, attributes) {
  548. set(
  549. key,
  550. '',
  551. assign({}, attributes, {
  552. expires: -1
  553. })
  554. );
  555. },
  556. withAttributes: function (attributes) {
  557. return init(this.converter, assign({}, this.attributes, attributes))
  558. },
  559. withConverter: function (converter) {
  560. return init(assign({}, this.converter, converter), this.attributes)
  561. }
  562. }, {
  563. attributes: {
  564. value: Object.freeze(defaultAttributes)
  565. },
  566. converter: {
  567. value: Object.freeze(converter)
  568. }
  569. })
  570. }
  571.  
  572. var api = init(defaultConverter, {
  573. path: '/'
  574. });
  575. /* eslint-enable no-var */
  576.  
  577. return api;
  578.  
  579. })))
  580. },
  581.  
  582. /*
  583. * @description base64转blob
  584. * @param {string} dataurl - base64的数据
  585. * @return {string} blob的链接
  586. * @example Utils.base64ToBlob("data:image/jpeg;base64,.....");
  587. * @exampleResult blob://xxxxxxx
  588. */
  589. Utils.base64ToBlob = (dataurl) => {
  590. if (typeof dataurl !== "string") {
  591. throw "参数 dataurl 类型必须为string类型";
  592. }
  593. var arr = dataurl.split(','),
  594. mime = arr[0].match(/:(.*?);/)[1],
  595. bstr = atob(arr[1]),
  596. n = bstr.length,
  597. u8arr = new Uint8Array(n);
  598. while (n--) {
  599. u8arr[n] = bstr.charCodeAt(n);
  600. }
  601. return new Blob([u8arr], {
  602. type: mime
  603. });
  604. },
  605.  
  606. /*
  607. * @description base64转File对象
  608. * @param {string} dataurl - base64的数据
  609. * @return {string} blob的链接
  610. * @example Utils.base64ToFile("data:image/jpeg;base64,.....");
  611. * @exampleResult object
  612. */
  613. Utils.base64ToFile = (dataurl, fileName) => {
  614. if (typeof dataurl !== "string") {
  615. throw "参数 dataurl 类型必须为string类型";
  616. }
  617. if (typeof fileName !== "string") {
  618. throw "参数 fileName 类型必须为string类型";
  619. }
  620. var arr = dataurl.split(','),
  621. mime = arr[0].match(/:(.*?);/)[1],
  622. bstr = atob(arr[1]),
  623. n = bstr.length,
  624. u8arr = new Uint8Array(n);
  625. while (n--) {
  626. u8arr[n] = bstr.charCodeAt(n);
  627. }
  628. return new File([u8arr], fileName, {
  629. type: mime
  630. });
  631. };
  632.  
  633. /*
  634. * @description blob转File对象
  635. * @param {string} theBlob - 需要转换的blob的链接
  636. * @param {string} fileName - 转换成的File对象的文件名称
  637. * @return {object} File对象
  638. * @example Utils.blobToFile("blob://xxxxx");
  639. * @exampleResult object
  640. */
  641. Utils.blobToFile = (theBlob, fileName) => {
  642. if (typeof theBlob !== "string") {
  643. throw "参数 theBlob 类型必须为string类型";
  644. }
  645. if (typeof fileName !== "string") {
  646. throw "参数 fileName 类型必须为string类型";
  647. }
  648. theBlob.lastModifiedDate = new Date();
  649. theBlob.name = fileName;
  650. return theBlob;
  651. },
  652.  
  653. /*
  654. * @description 同步File对象转base64
  655. * @param {object} file - 需要转换的File对象
  656. * @return {string} base64格式的数据
  657. * @example await Utils.asyncFileToBase64(object);
  658. * @exampleResult data:image/jpeg:base64/,xxxxxx
  659. */
  660. Utils.asyncFileToBase64 = (file) => {
  661. var reader = new FileReader();
  662. reader.readAsDataURL(file);
  663. return new Promise(res => {
  664. reader.onload = function (e) {
  665. res(e.target.result);
  666. }
  667. })
  668. };
  669.  
  670. /*
  671. * @description 下载base64格式的数据
  672. * @param {string} base64Content - 需要转换的base64数据
  673. * @param {string} fileName - 需要保存的文件名
  674. * @example Utils.downloadBase64("data:image/jpeg:base64/,xxxxxx");
  675. */
  676. Utils.downloadBase64 = (base64Content, fileName) => {
  677. var aLink = document.createElement('a');
  678. var blob = Utils.base64ToBlob(base64Content);
  679. var evt = document.createEvent('HTMLEvents');
  680. evt.initEvent('click', true, true) // initEvent 不加后两个参数在FF下会报错 事件类型,是否冒泡,是否阻止浏览器的默认行为
  681. aLink.download = fileName;
  682. aLink.href = URL.createObjectURL(blob);
  683. aLink.click();
  684. };
  685.  
  686. /*
  687. * @description 判断是否是手机访问
  688. * @return {boolean} - 返回如果是手机true,否则false
  689. * @example Utils.isPhone();
  690. * @exampleResult true
  691. */
  692. Utils.isPhone = () => {
  693. return Boolean(/(iPhone|iPad|iPod|iOS|Android)/i.test(navigator.userAgent));
  694. };
  695.  
  696. /*
  697. * @description 自定义字典,用于new
  698. * @example new let dictionary = Utils.Dictionary();
  699. * @example dictionary.set("xxx","xxx");
  700. * @example dictionary.get("xxx");
  701. * @example dictionary.has("xxx");
  702. */
  703. Utils.Dictionary = function () {
  704. this.items = {};
  705. //检查是否有某一个键
  706. this.has = function (key) {
  707. return this.items.hasOwnProperty(key);
  708. }
  709. //为字典添加某一个值
  710. this.set = function (key, val) {
  711. this.items[key] = val;
  712. }
  713. //删除某一个键
  714. this.delete = function (key) {
  715. if (this.has(key)) {
  716. delete this.items[key];
  717. return true;
  718. }
  719. return false;
  720. }
  721. //查找某一特定项
  722. this.get = function (key) {
  723. return this.has(key) ? this.items[key] : undefined;
  724. }
  725. //返回字典中的所有值
  726. this.values = function () {
  727. var res = [];
  728. for (var prop in this.items) {
  729. if (this.has(prop)) {
  730. res.push(this.items[prop]);
  731. }
  732. }
  733. return res;
  734. }
  735. //清空字典
  736. this.clear = function () {
  737. this.items = {};
  738. }
  739. //获取字典的长度
  740. this.size = function () {
  741. return Object.keys(this.items).length;
  742. }
  743. //获取字典所有的键
  744. this.keys = function () {
  745. return Object.keys(this.items);
  746. }
  747. //返回字典本身
  748. this.getItems = function () {
  749. return this.items;
  750. }
  751. };
  752.  
  753. /*
  754. * @description JSON数据从源端替换到目标端中,如果目标端存在该数据则替换,不添加,返回结果为目标端替换完毕的结果
  755. * @param {object} target - 目标端
  756. * @param {object} source - 源端
  757. * @example Utils.assignJSON({"1":1,"2":{"3":3}});
  758. * @exampleResult
  759. */
  760. Utils.assignJSON = (target,source) => {
  761. for (var target_key in target) {
  762. if (typeof source[target_key] !== "undefined") {
  763. if(typeof source[target_key] === "object"){
  764. target[target_key] = Utils.assignJSON(target[target_key],source[target_key]);
  765. }else{
  766. target[target_key] = source[target_key];
  767. }
  768. }
  769. };
  770. return target;
  771. }

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址