logo

常用工具类方法总结

Jun 6, 2023 · 9 min

写在前面 对于前端开发过程中一些常见的方法函数,都放置在 utils 的文件夹内,此处仅对工作中常用的一些方法做总结~
PS: 由于是根据项目内提取而来的工具函数~,不定期更新

存储localStorage#

export const setStorage = (name, content) => {
  if (!name) return;
  if (content) {
    content = JSON.stringify(content);
  }
  window.localStorage.setItem(name, content);
};

获取localStorage#

export const getStorage = name => {
  if (!name) return;
  const data = window.localStorage.getItem(name);
  if (data) {
    return JSON.parse(data);
  } else {
    return null;
  }
};

删除localStorage#

export const removeStorage = name => {
  if (!name) return;
  window.localStorage.removeItem(name);
};

存储sessionStorage#

export const setSessionStorage = (name, content) => {
  if (!name) return;
  if (content) {
    content = JSON.stringify(content);
  }
  window.sessionStorage.setItem(name, content);
};

获取sessionStorage#

export const getSessionStorage = name => {
  if (!name) return;
  return JSON.parse(window.sessionStorage.getItem(name));
};

删除sessionStorage#

export const removeSessionStorage = name => {
  if (!name) return;
  window.sessionStorage.removeItem(name);
};

下载文件#

/*
* @param {String} path - 下载地址/下载请求地址。
* @param {String} name - 下载文件的名字(考虑到兼容性问题,最好加上后缀名)
*/
export const downloadFile = (path) => {
  const xhr = new XMLHttpRequest();
  let fileType = path.substring(path.lastIndexOf('/') + 1);
  xhr.open('get', path);
  xhr.responseType = 'blob';
  xhr.send();
  xhr.onload = function () {
    if (this.status === 200 || this.status === 304) {
      const fileReader = new FileReader();
      fileReader.readAsDataURL(this.response);
      fileReader.onload = function () {
        const a = document.createElement('a');
        a.style.display = 'none';
        a.href = this.result;
        a.download = `${fileType}`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
      };
    }
  };
};

文件大小格式化#

export const formatFileSize = (bytes, decimalPoint = 2) => {
  if (bytes === 0) return '0 Bytes';
  const k = 1000;
  const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(decimalPoint)) + ' ' + sizes[i];
};

生成随机长度的字符串#

export const randomString = (len = 20) => {
  const chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz123456789';
  const strLen = chars.length;
  let randomStr = '';
  for (let i = 0; i < len; i++) {
    randomStr += chars.charAt(Math.floor(Math.random() * strLen));
  }
  return randomStr;
};

解析url地址参数#

/*
* @param url
* @param key
*/
export const getUrlParams = (url, key) => {
  if (!url) return;
  const params = (url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce(
  (a, v) => ((a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a),
  {},
  );
  if (key) {
    if (params[key]) {
      return params[key];
    } else {
      return null;
    }
  } else {
    return params;
  }
};

复制字符串到剪贴板#

export const copyToClipboard = str => {
  const el = document.createElement('textarea');
  el.value = str;
  el.setAttribute('readonly', '');
  el.style.position = 'absolute';
  el.style.left = '-9999px';
  document.body.appendChild(el);
  const selected = document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false;
  el.select();
  document.execCommand('copy');
  document.body.removeChild(el);
  if (selected) {
    document.getSelection().removeAllRanges();
    document.getSelection().addRange(selected);
  }
};

绑定事件#

/**
* @description 绑定事件 on(element, event, handler)
*/
export const on = (function () {
  if (document.addEventListener) {
    return function (element, event, handler) {
      if (element && event && handler) {
        element.addEventListener(event, handler, false);
      }
    };
  } else {
    return function (element, event, handler) {
      if (element && event && handler) {
        element.attachEvent('on' + event, handler);
      }
    };
  }
})();

解绑事件#

/**
* @description 解绑事件 off(element, event, handler)
*/
export const off = (function () {
  if (document.removeEventListener) {
    return function (element, event, handler) {
      if (element && event) {
        element.removeEventListener(event, handler, false);
      }
    };
  } else {
    return function (element, event, handler) {
      if (element && event) {
        element.detachEvent('on' + event, handler);
      }
    };
  }
})();

格式化时间戳#

/**
* timestamp 当前时间戳,毫秒
* format 时间格式(例如:YYYY-MM-DD hh:mm:ss):
*/
export const dateFormat = (timestamp, format) => {
  if (!timestamp) return;
  let date = new Date(timestamp);
  let o = {
    "M+": date.getMonth() + 1, //月
    "D+": date.getDate(), //天
    "W": "日一二三四五六".charAt(date.getDay()), //星期
    "h+": date.getHours(), //时
    "m+": date.getMinutes(), //分
    "s+": date.getSeconds(), //秒
    "q+": Math.floor((date.getMonth() + 3) / 3), //季节
    "S": date.getMilliseconds() //毫秒
  };
  if (/(Y+)/.test(format)) {
    format = format.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
  }
  for (let k in o) {
    if (new RegExp("(" + k + ")").test(format)) {
      format = format.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
    }
  }
  return format;
};

格式化时间(源数据单位 s)#

export const formatDateHms = (date = 0, format = '') => {
  const hours = Math.floor(date / 3600)
  .toString()
  .padStart(2, '0');
  const minute = Math.floor((date / 60) % 60)
  .toString()
  .padStart(2, '0');
  const second = Math.floor(date % 60)
  .toString()
  .padStart(2, '0');
  if (format === 'cn') {
    return `${hours}${minute}${second}`;
  } else {
    return `${hours}:${minute}:${second}`;
  }
};

查找指定节点的所有父节点#

export const findParentNode = (tree: any = [], id: string | number, target = 'id', includeChild = false) => {
  for (let i = 0, len = tree.length; i < len; i++) {
    // @ts-ignore
    const { children, ...other } = tree[i];
    if (tree[i][target] === id) {
      if (includeChild) {
        return [tree[i]];
      } else {
        return [other];
      }
    }
    if (children) {
      const node = findParentNode(children, id, target, includeChild);
      if (node !== undefined) {
        if (includeChild) {
          return node.concat(tree[i]);
        } else {
          return node.concat(other);
        }
      }
    }
  }
};

筛选两个数组不同的元素#

export function getArrayDiff(arr1, arr2) {
  return arr1.concat(arr2).filter((item, index, arr) => arr.indexOf(item) === arr.lastIndexOf(item));
}

动态加载JS#

export function dynamicLoadScript(url, async = false, onLoaded) {
  const script = document.createElement('script');
  script.type = 'text/javascript';
  script.onload = function () {
    onLoaded();
  };
  script.src = url;
  script.async = async;
  script.setAttribute('referrerpolicy', 'origin');
  document.getElementsByTagName('head')[0].appendChild(script);
}
> cd ..