zoukankan      html  css  js  c++  java
  • JS 常用方法汇总(不定期更新)

    /**
     * 获取当前日期
     * @returns {string}
     */
    Common.currentDate = function () {
      // 获取当前日期
      var date = new Date();
    
      // 获取当前月份
      var nowMonth = date.getMonth() + 1;
    
      // 获取当前是几号
      var strDate = date.getDate();
    
      // 添加分隔符“-”
      var seperator = "-";
    
      // 对月份进行处理,1-9月在前面添加一个“0”
      if (nowMonth >= 1 && nowMonth <= 9) {
        nowMonth = "0" + nowMonth;
      }
    
      // 对日期进行处理,1-9号在前面添加一个“0”
      if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
      }
    
      // 最后拼接字符串,得到一个格式为(yyyy-MM-dd)的日期
      return date.getFullYear() + seperator + nowMonth + seperator + strDate;
    };
    
    /**
     * 获取url上的参数(支持中文)
     * @param key
     * @returns {any}
     */
    Common.getUrlParam = function (key) {
      // 获取参数
      var url = window.location.search;
      // 正则筛选地址栏
      var reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)");
      // 匹配目标参数
      var result = url.substr(1).match(reg);
      //返回参数值
      return result ? decodeURIComponent(result[2]) : null;
    }
    
    /**
     * 数字千分位格式化
     * @param number 要格式化的数字
     * @param decimals 保留几位小数
     * @param dec_point 小数点符号
     * @param thousands_sep 千分位符号
     * @returns {string}
     */
    Common.numberFormat = function (number, decimals, dec_point, thousands_sep) {
      number = (number + '').replace(/[^0-9+-Ee.]/g, '');
      var n = !isFinite(+number) ? 0 : +number,
        prec = !isFinite(+decimals) ? 2 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
          var k = Math.pow(10, prec);
          return '' + Math.ceil(n * k) / k;
        };
    
      s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
      var re = /(-?d+)(d{3})/;
      while (re.test(s[0])) {
        s[0] = s[0].replace(re, "$1" + sep + "$2");
      }
    
      if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
      }
      return s.join(dec);
    };
    
    /**
     * 千分位格式化数字转为普通数字
     * @param formatedNum
     * @returns {number}
     */
    Common.rNumberFormat = function (formatedNum) {
      return parseFloat(formatedNum.replace(/[^d.-]/g, ""));
    };
    
    
    /**
     * 构造树型结构数据
     * @param {*} data 数据源
     * @param {*} id id字段 默认 'id'
     * @param {*} parentId 父节点字段 默认 'parentId'
     * @param {*} children 孩子节点字段 默认 'children'
     * @param {*} rootId 根Id 默认 0
     */
    Common.treeBuilder =  function(data, id, parentId, children, rootId) {
      id = id || 'id'
      parentId = parentId || 'parentId'
      children = children || 'children'
      rootId = rootId || 0
      //对源数据深度克隆
      const cloneData = JSON.parse(JSON.stringify(data))
      //循环所有项
      const treeData = cloneData.filter(father => {
        let branchArr = cloneData.filter(child => {
          //返回每一项的子级数组
          return father[id] === child[parentId]
        });
        branchArr.length > 0 ? father[children] = branchArr : '';
        //返回第一层
        return father[parentId] === rootId;
      });
      return treeData != '' ? treeData : data;
    };
    
    /**
     * 重新封装jQuery的 ajax方法
     **/
    var $ax = function (url, success, error) {
      this.url = url;
      this.type = "post";
      this.data = {};
      this.dataType = "json";
      this.async = false;
      this.success = success;
      this.error = error;
    };
    
    $ax.prototype = {
      start: function () {
        var me = this;
        var result = "";
    
        if (this.url.indexOf("?") === -1) {
          this.url = this.url + "?jstime=" + new Date().getTime();
        } else {
          this.url = this.url + "&jstime=" + new Date().getTime();
        }
    
        $.ajax({
          type: me.type,
          url: me.url,
          dataType: me.dataType,
          async: me.async,
          data: me.data,
          beforeSend: function (data) {
    
          },
          success: function (data) {
            result = data;
            if (me.success !== undefined) {
              me.success(data);
            }
          },
          error: function (data) {
            if (me.error !== undefined) {
              me.error(data);
            }
          }
        });
    
        return result;
      },
    
      set: function (key, value) {
        if (typeof key === "object") {
          for (var i in key) {
            if (typeof i === "function")
              continue;
            this.data[i] = key[i];
          }
        } else {
          this.data[key] = (typeof value === "undefined") ? $("#" + key).val() : value;
        }
        return this;
      },
    
      setData: function (data) {
        this.data = data;
        return this;
      },
    
      clear: function () {
        this.data = {};
        return this;
      }
    };
    
  • 相关阅读:
    MIne FirstBlog
    P6563 [SBCOI2020]一直在你身旁
    P6563 [SBCOI2020]一直在你身旁
    T122085 [SBCOI2020]时光的流逝
    LC 918. Maximum Sum Circular Subarray
    1026 Table Tennis
    LC 1442. Count Triplets That Can Form Two Arrays of Equal XOR
    LC 1316. Distinct Echo Substrings
    LC 493. Reverse Pairs
    1029 Median (二分)
  • 原文地址:https://www.cnblogs.com/liuyishi/p/13407314.html
Copyright © 2011-2022 走看看