Utils文件常见的JavaScript方法集合

目录
文章目录隐藏
  1. 1、数值单位转换
  2. 2、千分位转换
  3. 3、检查是否为空对象
  4. 4、path 后面增加 query 信息
  5. 5、检查是不是全面屏(移动端)
  6. 6、节流函数,控制函数重复执行的周期
  7. 7、new 图片对象来预加载
  8. 8、数组去重
  9. 9、对象数组去重
  10. 10、扁平数组与 JSON 树形互转
  11. 11、树形结构转扁平数组列表
  12. 12、动态加载脚本
  13. 13、动态加载 css
  14. 14、RequireJS 动态加载模块
  15. 15、统一日志打印
  16. 16、统一页面跳转方法
  17. 17、2 个数组合并成 1 个数组对象
  18. 18、在 data 数组中删除 obj 对象
  19. 19、通过属性值查找数组某一项
  20. 20、获取指定月份天数
  21. 21、判断时间是不是今天
  22. 22、对象判空
  23. 23、 数组对象属性值转换映射对象
  24. 24、首字母大写
  25. 25、判断两个字符串是否相等
  26. 26、js 判断对象中是否有某个属性
  27. 27、 检查一个数是否是整数则位数在 8 以内
  28. 28、判断字符串是否为空
  29. 29、验证是否为电话号码
  30. 30、获取文件的扩展名
  31. 31、字符串编码
  32. 32、字符串解码

Utils 文件常见的 JavaScript 方法集合

1、数值单位转换

export const numberUnitFormat = (value) => {
  let param = {};
  let k = 10000;
  let sizes = ['', '万', '亿', '万亿'];
  let i = null;
  if (value < k) {
    param.value = value;
    param.unit = '';
  } else {
    i = Math.floor(Math.log(value) / Math.log(k));
    param.value = (value / Math.pow(k, i)).toFixed(2);
    param.unit = sizes[i];
  }
  return param;
}

调用:

numberUnitFormat(23232323343.23) => { "value": "232.32", "unit": "亿" }

2、千分位转换

export const thousandFormat = (num, obj) => {
  let param = '';
  if (!obj) {
      //格式化千分位输出
      param = num.toLocaleString();
  } else if (obj && obj.lang === 'en') {
      //格式化为千分位带$符号输出
      param = num.toLocaleString('en', { style: 'currency', currency: 'USD' });
  } else if (obj && obj.lang === 'cn') {
      //格式化为带¥符号输出
      param = num.toLocaleString('cn', { style: 'currency', currency: 'CNY' });
  } else {
      //格式化千分位输出
      param = num.toLocaleString();
  }
  return param;
}

调用:

thousandFormat(123456789.0, { lang: 'cn' }) => ¥123,456,789.00

千分位转数值:

num.replace(/,/gi,'')

3、检查是否为空对象

/**
 * @param {Object} obj 被检查对象
 * @return {boolean} 检查结果
 */
 export function isEmptyObject(obj) {
  return obj && Object.keys(obj).length === 0;
}

4、path 后面增加 query 信息

/**
 * 如果 path 中有 ?则 query 用 & 连接,否则用 ?连接
 *
 * @param {string} path 路径信息
 * @param {Object} query query 参数
 * @return {string} 加上 query 的 path 结果
 */
 export const pathWithQuery = (path, query) => {
  return ~path.indexOf('?')
      ? `${path}&${queryStringify(query)}`
      : `${path}?${queryStringify(query)}`;
};

5、检查是不是全面屏(移动端)

/**
 * @return {boolean} 是不是全面屏机型
 */
 export const checkFullScreen = () => {
  try {
      return getSystemInfo().then(info => {
          const tempInfo = info.model.toLowerCase();
          return Promise.resolve([
              'iphone x',
              'iphone xr',
              'iphone xs',
              'iphone xs max',
              'iphone 11',
              'iphone 11 pro',
              'iphone 11 pro max',
              'iphone 12',
              'iphone 12 pro',
              'iphone 12 pro max'
          ].some(ele => tempInfo.includes(ele)));
      });
  } catch (err) {
      console.log('设备信息获取失败', err);
      Promise.resolve(false);
  }
};

6、节流函数,控制函数重复执行的周期

/**
 * @param {Function} fn 目标函数
 * @param {number} timeout 截流间隔时间
 * @return {Function} 待执行函数
 */
 export function throttle(fn, timeout = 500) {
  let lastApplyTime = 0;

  return function (...args) {
      const nowTime = Date.now();

      if (nowTime - lastApplyTime > timeout) {
          lastApplyTime = nowTime;
          return fn.apply(this, args);
      }
  };
}

7、new 图片对象来预加载

// 预加载图片缓存列表
const preImgList = [];

/**
 * 通过 new 图片对象来预加载图片
 * @param {string} url 图片地址
 *
 */
export function preloadImage(url = '') {
  const img = new Image();
  img.src = url;
  preImgList.push(img);
}

8、数组去重

/**
 * 如果是纯粹数组,用 es6 Set 去重,只需要传 arr 即可
 * @param  {} arr 数组 or 对象数组
 * @param  {} params 数组对象去重时根据 key 值去重
 */
export const uniq = (arr, params) => {
  if (!Array.isArray(data)) {
    return arr;
  }
  if (params) {
    let obj = {};
    let newArr = arr.reduce((perv, cur) => {
      obj[cur[params.key]]
        ? ''
        : (obj[cur[params.key]] = true && perv.push(cur));
      return perv;
    }, []);
    return newArr;
  } else {
    return Array.from(new Set(arr));
  }
};

调用:

uniq(data, { key: 'id' }) => 返回根据 ID 去重后的对象数组列表

9、对象数组去重

/**
 * 数组的对象完全匹配后去重
 * @param  {} data 对象数组
 */
export const uniqObject = (data) => {
  let uniques = [];
  let stringify = {};
  for (let i = 0; i < data.length; i++) {
    let keys = Object.keys(data[i]);
    keys.sort(function (a, b) {
      return Number(a) - Number(b);
    });
    let str = '';
    for (let j = 0; j < keys.length; j++) {
      str += JSON.stringify(keys[j]);
      str += JSON.stringify(data[i][keys[j]]);
    }
    if (!stringify.hasOwnProperty(str)) {
      uniques.push(data[i]);
      stringify[str] = true;
    }
  }
  uniques = uniques;
  return uniques;
};

调用:

uniqObject(data) => 返回去重后的对象数组列表

10、扁平数组与 JSON 树形互转

export const listToTree = (list, childName = 'children') => {
  const res = [];
  const map = list.reduce((res, v) => ((res[v.id] = v), res), {});

  for (const item of list) {
    if (item.parentId === 0) {
      res.push(item);
      continue;
    }
    if (item.parentId in map) {
      const parent = map[item.parentId];
      parent[childName] = parent[childName] || [];
      parent[childName].push(item);
    }
  }
  return res;
}

调用:

listToTree(data) => 返回树形数组

11、树形结构转扁平数组列表

export const treeToList = (data, childName = 'children') => {
  // if (!Array.isArray(data)) {
  // 	return [];
  // }
  return data.reduce(
    (prev, cur) =>
      prev.concat([cur], treeToList(cur[childName] || [])),
    []
  );
};

调用:

treeToList(data) => 返回扁平数组列表

12、动态加载脚本

export const dynamicJsLoading (jsPath, callback, async, afterJs) {
  var js = $("script[src='" + jsPath + "']");
  if (js.length > 0) return;

  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = jsPath;
  var fn = callback || function () { };
  if (async) {
    script.setAttribute("async", true);
    script.setAttribute("defer", "");

    if (script.readyState) {//IE
      script.onreadystatechange = function () {
        if (script.readyState == 'loaded' || script.readyState == 'complete') {
          script.onreadystatechange = null;
          console.log("dynamicJsLoading");
          fn();
        }
      };
    } else {//其他浏览器        
      script.onwaiting = function () {
        console.log("dynamicJsLoading");
        fn();
      };
      script.onload = function () {
        console.log("dynamicJsLoading");
        script.onload = null;
        fn();
      };
    }
  }

  if (afterJs) {
    $("script[src*='" + afterJs + "']").last().after(script);
  }
  else {
    // document.getElementsByTagName("head")[0].appendChild(script);
    $("script[src*='jquery.min']").last().after(script);
  }

  if (!async)
    fn();
};

13、动态加载 css

export const dynamicCssLoading (cssPath, callback, afterCss) {
  var css = $("link[href='" + cssPath + "']");
  if (css.length > 0) return;

  var css = document.createElement('link');
  css.rel = 'stylesheet';
  css.href = cssPath;

  if (afterCss) {
    $("link[href*='" + afterCss + "']").last().after(css);
  }
  else {
    // document.getElementsByTagName("head")[0].appendChild(script);
    $("head").last().append(css);
  }

  if (callback)
    callback();
}

14、RequireJS 动态加载模块

/**
*  @isWinobj  
*  @moduleName 模块名称
**/
export const dynamicRequireJS = (moduleName, isWinobj) => {
  if (isWinobj) {
    if (!window[moduleName]) {
      window[moduleName] = require(moduleName);
    }
    return window[moduleName];
  } else {
    return require(moduleName);
  }
}

15、统一日志打印

export function pathWithQuery(log) {
  if (true === util.debug) {
    console.log(log);
  }
}

16、统一页面跳转方法

/**
 * @param {*跳转类型} type 
 * @param {*跳转地址} url 
 */
export const goPage = (type, url) => {
  switch (type) {
    //页面跳转
    case 1:
      window.location.href = url;
      break;
    //返回上一个页面
    case 2:
      window.history.go(-1);
      break;
    //返回并刷新上一个页面
    case 3:
      window.location.href = document.referrer;
  }
};

17、2 个数组合并成 1 个数组对象

/**
 * @param {*} arr1 数组 1
 * @param {*} arr2 数组 2
 * @param {*} param1 
 * @param {*} param2 
 * @returns 
 */
export const arrayMerge = (arr1, arr2, param1, param2) => {
  var newArray = [];
  $.each(arr1, function (i, v) {
    var obj = {};
    obj[param1] = v;
    $.each(arr2, function (j, k) {
      if (i === j) {
        obj[param2] = k;
      }
    })
    newArray.push(obj);
  });
  return newArray;
};

18、在 data 数组中删除 obj 对象

export const remove = (data, obj) => {
  for (var i = 0; i < data.length; i++) {
    if (data[i] == obj) {
      //删除下标为 i 的元素
      data.splice(i, 1);
    }
  }
  return data;
}

19、通过属性值查找数组某一项

export function findArrItemByPropVal(arr, prop, val) {
  let result = null;
  for (let i = 0, l = arr.length; i < l; i++) {
    if (arr[i][prop] === val) {
      result = arr[i];
      break;
    }
  }
  return result;
}

20、获取指定月份天数

export function getDateByMon(year, month) {
  let d = new Date(year, month, 0);
  return d.getDate();
}

21、判断时间是不是今天

export function isTodayDate(time) {
  if (time.toDateString() === new Date().toDateString()) {
    return true;
  } else {
    return false;
  }
}

22、对象判空

export function isObjEmpty(obj) {
  for (let key in obj) {
    return false;// 非空
  }
  return true;// 为空
}

调用:

isObjEmpty( {sex: "male"}) --> 布尔类型 false

23、 数组对象属性值转换映射对象

export function arrPropValToMap(arr, format) {
  const pArr = format.split(':');
  const p1 = pArr[0];
  const p2 = pArr[1];
  let res = {};
  for (let i = 0, l = arr.length; i < l; i++) {
    let v1 = arr[i][p1];
    let v2 = arr[i][p2];
    res[v1] = v2
  }
  return res;
}

调用:

arrPropValToMap('[{a: c, b: d}] ','a:b') --> {c: d})

24、首字母大写

export const capitalizeFirstLetter = (string) => {
  return string.charAt(0).toUpperCase() + string.slice(1);
};

调用:

capitalizeFirstLetter('promise') => Promise

25、判断两个字符串是否相等

/**
 * 相等返回 true 否则返回 false
 *
 * @param {} source
 * @param {} target
 */
export function decideString(source, target) {
  return (source == target) ? true : false;
}

调用:

decideString('abcd','sdasc')  --> 布尔类型 false

26、js 判断对象中是否有某个属性

/**
 * @param {*} obj 对象
 * @param {*} params 参数
 * @returns 
 */
export const isHasOwnPro = (obj, params) => {
  if (obj.hasOwnProperty(params)) {
    return true;
  } else {
    return false;
  }
}

调用:

isHasOwnPro({sex: "male"},'sex')  --> true

27、 检查一个数是否是整数则位数在 8 以内

/**
 * @param {} source
 */
export function checkIntLeng(source) {
  var regex = /^[1-9]{1}[0-9]{1,7}$/g
  return regex.test(source);
}

28、判断字符串是否为空

/**
 * 若为空则返回 true 否则返回 false
 * @param source
 * @return true 或者 false
 **/
export function isEmptyString(source) {
  var str = source.replace(/(^\s*)|(\s*$)/g, "");
  if (str == "" || str.toLowerCase() == "null" || str.length <= 0) {
    return true;
  } else {
    return false;
  }
}

调用:

isEmptyString('dasedfeaw') ---> false

29、验证是否为电话号码

/**
 * 验证是否为座机号码
 * @param {} source
 */

export function isTelephone(source) {
  var regex = /^(0[0-9]{2,3}\-)?([2-9][0-9]{6,7})+(\-[0-9]{1,4})?$/
  return regex.test(source);
}

/**
* 验证是否移动手机
* @param {}source
*/

export function isMobilePhone(source) {
  var regex = /^((\(\d{3}\))|(\d{3}\-))?1\d{10}/;
  return regex.test(source);
}

30、获取文件的扩展名

/**
 * @param {} filename 文件
 */
export function getFileExt(filename) {
  var d = /\.[^\.]+$/.exec(filename);
  var ext = new String(d);
  var s = ext.toLowerCase();
  return s;
}

31、字符串编码

export function strEncode(source) {
  return encodeURIComponent(source);
}

32、字符串解码

export function strDencode(source) {
  return decodeURIComponent(source);
}

相关文章推荐:

「点点赞赏,手留余香」

2

给作者打赏,鼓励TA抓紧创作!

微信微信 支付宝支付宝

还没有人赞赏,快来当第一个赞赏的人吧!

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
码云笔记 » Utils文件常见的JavaScript方法集合

发表回复