JS 常用方法整理

/**
 * 获取浏览器地址上的参数
 * @name 参数名
 * */
export const getUrlParam = (name) => {
  const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
  const { hash, search } = window.location;
  const result = ((hash || search).split('?')[1] || '').match(reg);
  return result ? decodeURIComponent(result[2]) : null;
}
export function getUrlParams(name){
    const { hash, search } = window.location;
    const arr = ((hash || search).split('?')[1] || '').split("&");
    const params = {};
    for(let i=0; i {
  return Math.floor((max - min) * Math.random() + min);
};

/**
 * 数组去重
 * @param {array} 原数组
 * @param {string} 重复字段名称(可不传)
 */
export function setUnique(arr, refield) {
  let brr = [];
  for (let i = 0; i < arr.length; i++) {
    for (let j = i + 1; j < arr.length; j++) {
      if (refield) {
        if (arr[i][refield] === arr[j][refield]) {
          ++i;
        }
      } else if (arr[i] === arr[j]) {
        ++i;
      }
    }
    brr.push(arr[i]);
  }
  return brr;
}

/**
 * 移动数组(包含对象)其中一项的位置
 * @param data 原数据 例 [{name:'Jack'},{name:'Tom'},{name:'Bob'}]
 *  @param key 字段名 例 name
 * @param value 值 例 Tom
 */
export const onMoveData = (data, key, value) => {
//会改变原数据,若不想改变,要对data进行深拷贝
  for(let i = 0, len = data.length; i < len; i++){
    if(data[i][key] === value){
      let item = data.splice(i,1);
      console.log(item);
      data.unshift(item[0]); //移到最前
      // data.push(item[0]); //移到最后
      // data.splice(j, 0, item[0]); //移到任意位置j
      return data
    }
  }
  return data
};
export const copyText = (text) => {
    var oInput = document.createElement('input');
    oInput.value = text;
    document.body.appendChild(oInput);
    oInput.select(); // 选择对象
    document.execCommand("Copy"); // 执行浏览器复制命令
    oInput.style.display='none';
    //message.success("复制成功");
    //Toast.success("复制成功");
  }

/**
 * Base64编码解码
 * */
export const Base64 = {
    _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
    encode: function(e) {
        var t = "";
        var n, r, i, s, o, u, a;
        var f = 0;
        e = Base64._utf8_encode(e);
        while (f < e.length) {
            n = e.charCodeAt(f++);
            r = e.charCodeAt(f++);
            i = e.charCodeAt(f++);
            s = n >> 2;
            o = (n & 3) << 4 | r >> 4;
            u = (r & 15) << 2 | i >> 6;
            a = i & 63;
            if (isNaN(r)) {
                u = a = 64
            } else if (isNaN(i)) {
                a = 64
            }
            t = t + this._keyStr.charAt(s) + this._keyStr.charAt(o) + this._keyStr.charAt(u) + this._keyStr.charAt(a)
        }
        return t
    },
    decode: function(e) {
        var t = "";
        var n, r, i;
        var s, o, u, a;
        var f = 0;
        e = e.replace(/[^A-Za-z0-9+/=]/g, "");
        while (f < e.length) {
            s = this._keyStr.indexOf(e.charAt(f++));
            o = this._keyStr.indexOf(e.charAt(f++));
            u = this._keyStr.indexOf(e.charAt(f++));
            a = this._keyStr.indexOf(e.charAt(f++));
            n = s << 2 | o >> 4;
            r = (o & 15) << 4 | u >> 2;
            i = (u & 3) << 6 | a;
            t = t + String.fromCharCode(n);
            if (u != 64) {
                t = t + String.fromCharCode(r)
            }
            if (a != 64) {
                t = t + String.fromCharCode(i)
            }
        }
        t = Base64._utf8_decode(t);
        return t
    },
    _utf8_encode: function(e) {
        e = e.replace(/rn/g, "n");
        var t = "";
        for (var n = 0; n < e.length; n++) {
            var r = e.charCodeAt(n);
            if (r < 128) {
                t += String.fromCharCode(r)
            } else if (r > 127 && r < 2048) {
                t += String.fromCharCode(r >> 6 | 192);
                t += String.fromCharCode(r & 63 | 128)
            } else {
                t += String.fromCharCode(r >> 12 | 224);
                t += String.fromCharCode(r >> 6 & 63 | 128);
                t += String.fromCharCode(r & 63 | 128)
            }
        }
        return t
    },
    _utf8_decode: function(e) {
        var t = "";
        var n = 0;
        var r = 0;
                var c2 = 0;
                var c3 = 0;
        while (n < e.length) {
            r = e.charCodeAt(n);
            if (r < 128) {
                t += String.fromCharCode(r);
                n++
            } else if (r > 191 && r < 224) {
                c2 = e.charCodeAt(n + 1);
                t += String.fromCharCode((r & 31) << 6 | c2 & 63);
                n += 2
            } else {
                c2 = e.charCodeAt(n + 1);
                c3 = e.charCodeAt(n + 2);
                t += String.fromCharCode((r & 15) << 12 | (c2 & 63) << 6 | c3 & 63);
                n += 3
            }
        }
        return t
    }
}
/**
 * 格式化时间
 * @param date yyyymmddHHMMSS
 * @returns mm月dd日 HH:MM
 */
export function formatDate(date, format, type) {
    if (date === null || date === undefined || date === "null") {
        return "";
    }
    switch (format) {
        // 年月
        case "yyyymm":
            return date.substring(0, 4) + (type || "年") + date.substring(4, 6) + (type ? "" : "月");
            break;
        // 年月日
        case "yyyymmdd":
            return date.substring(0, 4) + (type || "年") + date.substring(4, 6) + (type || "月") + date.substring(6, 8) + (type ? " " : "日");
            break;
        // 年月日时分
        case "yyyymmddHHMM":
            return date.substring(0, 4) + (type || "年") + date.substring(4, 6) + (type || "月") + date.substring(6, 8) + (type ? " " : "日") +
                date.substring(8, 10) + ":" + date.substring(10, 12);
            break;
        // 年月日时分秒
        case "yyyymmddHHMMSS":
            return date.substring(0, 4) + (type || "年") + date.substring(4, 6) + (type || "月") + date.substring(6, 8) + (type ? " " : "日") +
                date.substring(8, 10) + ":" + date.substring(10, 12) + ":" + date.substring(12, 14)
            break;
        // 月日时分秒
        case "mmddHHMMSS":
            return date.substring(4, 6) + (type || "月") + date.substring(6, 8) + (type ? " " : "日") +
                date.substring(8, 10) + ":" + date.substring(10, 12) + ":" + date.substring(12, 14);
            break;
        // 月日时分
        default:
            return date.substring(4, 6) + (type || "月") + date.substring(6, 8) + (type ? " " : "日") +
                date.substring(8, 10) + ":" + date.substring(10, 12);
    }
}
export function dateFormat(timestamp, formats) {
    formats = formats || 'yyyy-mm-dd';
    var zero = function (value) {
        if (value < 10) {
            return '0' + value;
        }
        return value;
    };

    var myDate = timestamp ? new Date(timestamp) : new Date();

    var year = myDate.getFullYear();
    var month = zero(myDate.getMonth() + 1);
    var day = zero(myDate.getDate());

    var hour = zero(myDate.getHours());
    var minite = zero(myDate.getMinutes());
    var second = zero(myDate.getSeconds());

    return formats.replace(/yyyy|mm|dd|HH|MM|SS/ig, function (matches) {
        return ({
            yyyy: year,
            mm: month,
            dd: day,
            HH: hour,
            MM: minite,
            SS: second
        })[matches];
    });
};

你可能感兴趣的:(JS 常用方法整理)