utils.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /**
  2. * 随机选取数组中的一个值
  3. */
  4. function randomSelectOne(arr) {
  5. return arr[Math.floor(Math.random()*(arr.length -1))];
  6. }
  7. /**
  8. * 随机选取数组中的N个值
  9. */
  10. function randomSelectN(arr) {
  11. let MAX = Math.floor(Math.random()*(arr.length - 1));
  12. return arr.slice(0, MAX);
  13. }
  14. /**
  15. * 解析url中参数
  16. */
  17. export function getUrlParams(url) {
  18. const d = decodeURIComponent;
  19. let queryString = url ? url.split('?')[1] : window.location.search.slice(1);
  20. const obj = {};
  21. if (queryString) {
  22. queryString = queryString.split('#')[0]; // eslint-disable-line
  23. const arr = queryString.split('&');
  24. for (let i = 0; i < arr.length; i += 1) {
  25. const a = arr[i].split('=');
  26. let paramNum;
  27. const paramName = a[0].replace(/\[\d*\]/, (v) => {
  28. paramNum = v.slice(1, -1);
  29. return '';
  30. });
  31. const paramValue = typeof (a[1]) === 'undefined' ? true : a[1];
  32. if (obj[paramName]) {
  33. if (typeof obj[paramName] === 'string') {
  34. obj[paramName] = d([obj[paramName]]);
  35. }
  36. if (typeof paramNum === 'undefined') {
  37. obj[paramName].push(d(paramValue));
  38. } else {
  39. obj[paramName][paramNum] = d(paramValue);
  40. }
  41. } else {
  42. obj[paramName] = d(paramValue);
  43. }
  44. }
  45. }
  46. return obj;
  47. }
  48. module.exports = {
  49. randomSelectOne,
  50. randomSelectN,
  51. getUrlParams,
  52. }