常用JS方法

import { validatenull } from "./validate";
//表单序列化
export const serialize = (data) => {
  let list = [];
  Object.keys(data).forEach((ele) => {
    list.push(`${ele}=${data[ele]}`);
  });
  return list.join("&");
};
export const getObjType = (obj) => {
  var toString = Object.prototype.toString;
  var map = {
    "[object Boolean]": "boolean",
    "[object Number]": "number",
    "[object String]": "string",
    "[object Function]": "function",
    "[object Array]": "array",
    "[object Date]": "date",
    "[object RegExp]": "regExp",
    "[object Undefined]": "undefined",
    "[object Null]": "null",
    "[object Object]": "object",
  };
  if (obj instanceof Element) {
    return "element";
  }
  return map[toString.call(obj)];
};
export const getViewDom = () => {
  return window.document
    .getElementById("avue-view")
    .getElementsByClassName("el-scrollbar__wrap")[0];
};
/**
 * 对象深拷贝
 */
export const deepClone = (data) => {
  var type = getObjType(data);
  var obj;
  if (type === "array") {
    obj = [];
  } else if (type === "object") {
    obj = {};
  } else {
    //不再具有下一层次
    return data;
  }
  if (type === "array") {
    for (var i = 0, len = data.length; i < len; i++) {
      obj.push(deepClone(data[i]));
    }
  } else if (type === "object") {
    for (var key in data) {
      obj[key] = deepClone(data[key]);
    }
  }
  return obj;
};
/**
 * 设置灰度模式
 */
export const toggleGrayMode = (status) => {
  if (status) {
    document.body.className = document.body.className + " grayMode";
  } else {
    document.body.className = document.body.className.replace(" grayMode", "");
  }
};
/**
 * 设置主题
 */
export const setTheme = (name) => {
  document.body.className = name;
};

/**
 * 加密处理
 */
export const encryption = (params) => {
  let { data, type, param, key } = params;
  let result = JSON.parse(JSON.stringify(data));
  if (type == "Base64") {
    param.forEach((ele) => {
      result[ele] = btoa(result[ele]);
    });
  } else if (type == "Aes") {
    param.forEach((ele) => {
      result[ele] = window.CryptoJS.AES.encrypt(result[ele], key).toString();
    });
  }
  return result;
};

/**
 * 浏览器判断是否全屏
 */
export const fullscreenToggel = () => {
  if (fullscreenEnable()) {
    exitFullScreen();
  } else {
    reqFullScreen();
  }
};
/**
 * esc监听全屏
 */
export const listenfullscreen = (callback) => {
  function listen () {
    callback();
  }

  document.addEventListener("fullscreenchange", function () {
    listen();
  });
  document.addEventListener("mozfullscreenchange", function () {
    listen();
  });
  document.addEventListener("webkitfullscreenchange", function () {
    listen();
  });
  document.addEventListener("msfullscreenchange", function () {
    listen();
  });
};
/**
 * 浏览器判断是否全屏
 */
export const fullscreenEnable = () => {
  var isFullscreen =
    document.isFullScreen ||
    document.mozIsFullScreen ||
    document.webkitIsFullScreen;
  return isFullscreen;
};

/**
 * 浏览器全屏
 */
export const reqFullScreen = () => {
  if (document.documentElement.requestFullScreen) {
    document.documentElement.requestFullScreen();
  } else if (document.documentElement.webkitRequestFullScreen) {
    document.documentElement.webkitRequestFullScreen();
  } else if (document.documentElement.mozRequestFullScreen) {
    document.documentElement.mozRequestFullScreen();
  }
};
/**
 * 浏览器退出全屏
 */
export const exitFullScreen = () => {
  if (document.documentElement.requestFullScreen) {
    document.exitFullScreen();
  } else if (document.documentElement.webkitRequestFullScreen) {
    document.webkitCancelFullScreen();
  } else if (document.documentElement.mozRequestFullScreen) {
    document.mozCancelFullScreen();
  }
};
/**
 * 递归寻找子类的父类
 */

export const findParent = (menu, id) => {
  for (let i = 0; i < menu.length; i++) {
    if (menu[i].children.length != 0) {
      for (let j = 0; j < menu[i].children.length; j++) {
        if (menu[i].children[j].id == id) {
          return menu[i];
        } else {
          if (menu[i].children[j].children.length != 0) {
            return findParent(menu[i].children[j].children, id);
          }
        }
      }
    }
  }
};
/**
 * 判断2个对象属性和值是否相等
 */

/**
 * 动态插入css
 */

export const loadStyle = (url) => {
  const link = document.createElement("link");
  link.type = "text/css";
  link.rel = "stylesheet";
  link.href = url;
  const head = document.getElementsByTagName("head")[0];
  head.appendChild(link);
};
/**
 * 判断路由是否相等
 */
export const diff = (obj1, obj2) => {
  delete obj1.close;
  var o1 = obj1 instanceof Object;
  var o2 = obj2 instanceof Object;
  if (!o1 || !o2) {
    /*  判断不是对象  */
    return obj1 === obj2;
  }

  if (Object.keys(obj1).length !== Object.keys(obj2).length) {
    return false;
    //Object.keys() 返回一个由对象的自身可枚举属性(key值)组成的数组,例如:数组返回下表:let arr = ["a", "b", "c"];console.log(Object.keys(arr))->0,1,2;
  }

  for (var attr in obj1) {
    var t1 = obj1[attr] instanceof Object;
    var t2 = obj2[attr] instanceof Object;
    if (t1 && t2) {
      return diff(obj1[attr], obj2[attr]);
    } else if (obj1[attr] !== obj2[attr]) {
      return false;
    }
  }
  return true;
};
/**
 * 根据字典的value显示label
 */

// 回显数据字典(字符串数组)
export const findByvalue = (dic, value) => {
  let result = "";
  if (validatenull(dic)) return value;
  if (
    typeof value == "string" ||
    typeof value == "number" ||
    typeof value == "boolean"
  ) {
    let index = 0;
    index = findArray(dic, value);
    if (index != -1) {
      result = dic[index].dictValue || dic[index].monitorName;
    } else {
      result = value;
    }
  } else if (value instanceof Array) {
    result = [];
    let index = 0;
    value.forEach((ele) => {
      index = findArray(dic, ele);
      if (index != -1) {
        let label = dic[index].dictValue || dic[index].monitorName;
        result.push(label);
      } else {
        result.push(value);
      }
    });
    result = result.toString();
  }
  return result;
};
export const findByvalue2 = (dic, value, targetName, targetKey) => {
  let result = "";
  if (validatenull(dic)) return value;
  if (
    typeof value == "string" ||
    typeof value == "number" ||
    typeof value == "boolean"
  ) {
    let index = 0;
    index = findArray2(dic, value, targetKey);
    if (index != -1) {
      result = dic[index][targetName];
    } else {
      result = value;
    }
  } else if (value instanceof Array) {
    result = [];
    let index = 0;
    value.forEach((ele) => {
      index = findArray2(dic, ele, targetKey);
      if (index != -1) {
        let label = dic[index][targetName];
        result.push(label);
      } else {
        result.push(value);
      }
    });
    result = result.toString();
  }
  return result;
};
/**
 * 根据字典的value查找对应的index
 */
export const findArray2 = (dic, value, targetKey) => {
  for (let i = 0; i < dic.length; i++) {
    let keyVal = dic[i][targetKey];
    if (keyVal == value) {
      return i;
    }
  }
  return -1;
};
/**
 *遍历树结构,通过id获取对应的label
 */
export const findTreeName = (list, id) => {
  let _this = this;
  for (let i = 0; i < list.length; i++) {
    let a = list[i];
    if (a.id === id) {
      return a.title;
    } else {
      if (a.children && a.children.length > 0) {
        let res = findTreeName(a.children, id);
        if (res) {
          return res;
        }
      }
    }
  }
};

/**
 *遍历树结构,通过id获取对应的obj
 */
export const findTreeObj = (list, id) => {
  let _this = this;
  for (let i = 0; i < list.length; i++) {
    let a = list[i];
    if (a.id === id) {
      return a;
    } else {
      if (a.children && a.children.length > 0) {
        let res = findTreeObj(a.children, id);
        if (res) {
          return res;
        }
      }
    }
  }
};

export const findcheckbox = (list, id) => {
  let _this = this;
  for (let i = 0; i < list.length; i++) {
    let a = list[i];
    if (a.layerName === id) {
      return a;
    } else {
      if (a.children && a.children.length > 0) {
        let res = findTreeObj(a.children, id);
        if (res) {
          return res;
        }
      }
    }
  }
};
/**
 * 根据字典的value查找对应的index
 */
export const findArray = (dic, value) => {
  for (let i = 0; i < dic.length; i++) {
    let keyVal = dic[i].dictKey || dic[i].monitorCode;
    if (keyVal == value) {
      return i;
    }
  }
  return -1;
};

/**
 * 根据字典的value查找对应的对象
 */
export const findDictObj = (dic, value) => {
  for (let i = 0; i < dic.length; i++) {
    let id = dic[i].dictKey || dic[i].id;
    if (id == value) {
      return dic[i];
    }
  }
  return {};
};
/**
 * 生成随机len位数字
 */
export const randomLenNum = (len, date) => {
  let random = "";
  random = Math.ceil(Math.random() * 100000000000000)
    .toString()
    .substr(0, len ? len : 4);
  if (date) random = random + Date.now();
  return random;
};
/**
 * 打开小窗口
 */
export const openWindow = (url, title, w, h) => {
  // Fixes dual-screen position                            Most browsers       Firefox
  const dualScreenLeft =
    window.screenLeft !== undefined ? window.screenLeft : screen.left;
  const dualScreenTop =
    window.screenTop !== undefined ? window.screenTop : screen.top;

  const width = window.innerWidth
    ? window.innerWidth
    : document.documentElement.clientWidth
      ? document.documentElement.clientWidth
      : screen.width;
  const height = window.innerHeight
    ? window.innerHeight
    : document.documentElement.clientHeight
      ? document.documentElement.clientHeight
      : screen.height;

  const left = width / 2 - w / 2 + dualScreenLeft;
  const top = height / 2 - h / 2 + dualScreenTop;
  const newWindow = window.open(
    url,
    title,
    "toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=yes, copyhistory=no, width=" +
    w +
    ", height=" +
    h +
    ", top=" +
    top +
    ", left=" +
    left
  );

  // Puts focus on the newWindow
  if (window.focus) {
    newWindow.focus();
  }
};

/**
 * 获取顶部地址栏地址
 */
export const getTopUrl = () => {
  return window.location.href.split("/#/")[0];
};

/**
 * 获取url参数
 * @param name 参数名
 */
export const getQueryString = (name) => {
  let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
  let r = window.location.search.substr(1).match(reg);
  if (r != null) return unescape(decodeURI(r[2]));
  return null;
};

/**
 * 下载文件
 * @param {String} path - 文件地址
 * @param {String} name - 文件名,eg: test.png
 */
export const downloadFileBlob = (path, name) => {
  const xhr = new XMLHttpRequest();
  xhr.open("get", path);
  xhr.responseType = "blob";
  xhr.send();
  xhr.onload = function () {
    if (this.status === 200 || this.status === 304) {
      // 如果是IE10及以上,不支持download属性,采用msSaveOrOpenBlob方法,但是IE10以下也不支持msSaveOrOpenBlob
      if ("msSaveOrOpenBlob" in navigator) {
        navigator.msSaveOrOpenBlob(this.response, name);
        return;
      }
      const url = URL.createObjectURL(this.response);
      const a = document.createElement("a");
      a.style.display = "none";
      a.href = url;
      a.download = name;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
    }
  };
};

/**
 * 下载文件
 * @param {String} path - 文件地址
 * @param {String} name - 文件名,eg: test.png
 */
export const downloadFileBase64 = (path, name) => {
  const xhr = new XMLHttpRequest();
  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 = name;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
      };
    }
  };
};


/**
 * 下载文件
 * @param {String} res - 文件地址
 * @param {String} type -类型
 */
export const downloadFileliu = (res, type) => {
  type = type ? type : 'application/vnd.ms-excel'
  let fileNames = res.headers['content-disposition']
  let blob = new Blob([res.data], { type: type })
  let fileName = ''
  if (fileNames.indexOf('"') > 0) {
    fileName = decodeURI(fileNames.match(/"(.*)"$/)[1])
  } else {
    fileName = decodeURI(fileNames.match(/=(.*)$/)[1])
  }
  if ('download' in document.createElement('a')) {
    // 非IE下载
    const elink = document.createElement('a')
    elink.download = fileName
    elink.style.display = 'none'
    elink.href = URL.createObjectURL(blob)
    document.body.appendChild(elink)
    elink.click()
    URL.revokeObjectURL(elink.href) // 释放URL 对象
    document.body.removeChild(elink)
  } else {
    // IE10+下载
    navigator.msSaveBlob(blob, fileName)
  }
};

/**
 * 遍历树结构
 * @param {String, Number} value - 根据此值去树结构里遍历
 * @param {String} targetField - 需要和树结构里哪个字段比较
 * @param {Array} arr - 目标树结构
 */
export const findTreeItem = (value, targetField, arr) => {
  for (let i = 0; i < arr.length; i++) {
    let item = arr[i];
    if (item[targetField] == value) {
      return item;
    } else {
      if (item.children && item.children.length > 0) {
        let res = findTreeItem(value, targetField, item.children);
        if (res) {
          return res;
        }
      }
    }
  }
};

/**
 * 遍历树结构,获取符合条件的数据
 * @param {String, Number} value - 需要获取的字段
 * @param {String} targetField - 需要和树结构里哪个字段比较
 * @param {String} targetValue - 需要比较的值
 * @param {Array} arr - 目标树结构
 */
export const getTreeValues = (value, targetField, arr, targetValue) => {
  debugger;
  let result;
  for (let i = 0; i < arr.length; i++) {
    let item = arr[i];
    if (item[targetField] === targetValue) {
      return item[value];
    } else {
      if (item.children && item.children.length > 0) {
        let res = getTreeValues(value, targetField, item.children, targetValue);
        if (res) {
          return res;
        }
      }
    }
  }
};
//表格行class
export const rowClassName = (record, index) => {
  return index % 2 ? "table-rows-1" : "table-rows-2";
};

export const findSome = (arr, key, string) => {
  let _item = undefined;
  arr.map((item) => {
    if (item.list && item.list.length) {
      item.list.map((__item) => {
        if (__item[key] === string) {
          _item = __item;
        }
      });
    } else {
      if (item[key] === string) {
        _item = item;
      }
    }
  });
  return _item;
};

//查找第一个子数据
export const getFirstChild = (arr) => {
  let _data;
  let _arr = arr[0];
  if (_arr.list && _arr.list.length) {
    let data = getFirstChild(_arr.list);
    _data = data;
  } else {
    _data = _arr;
  }
  return _data;
};

//拍平数组
export const flattenArray = (arr, str, del) => {
  var list = [];
  arr.map((item) => {
    list.push(item);
    if (item[str]) {
      let _list = flattenArray(item[str], str);
      list.push(..._list);
    }
  });
  //删除
  if (del) list.map((_item) => delete _item[str]);
  return list;
};

//guid
export const guid = () => {
  const s4 = () =>
    Math.floor((1 + Math.random()) * 0x10000)
      .toString(16)
      .substring(1);
  return (() =>
    `${s4() + s4()}-${s4()}-${s4()}-${s4()}-${s4()}${s4()}${s4()}`)();
};
//数组过滤
export const fiterArry = (arrs1, arr2) => {
  const result = arrs1.filter((item) => !arr2.includes(item));
  return result;
};


/*删除数组中的某一个对象
   _arr:数组
   _obj:需删除的对象
   */
export const removeAaary = (_arr, _obj) => {
  var length = _arr.length;
  for (var i = 0; i < length; i++) {
    if (_arr[i] == _obj) {
      _arr.splice(i, 1); //删除下标为i的元素
      return _arr;
    }
  }
}


export const findobjct = (_name, _obj) => {

  const items = _obj.filter(item => {
    return item.prop == _name
  })[0]
  return items
}

/**
 * 获取不同等级下的颜色
 * @param {Object} obj
 * @param obj.colorList 颜色列表
 * @param obj.value     数据的值对应的字段名称   例如 'value'
 * @param obj.label     数据的说明对应的颜色 例如 'label'
 * @param obj.data      当前传入的数据值
 * @return color        返回当前传入值在数组中对应的颜色
 */
export const getDataColor = (obj) => {
  let color = "";
  if (Array.isArray(obj.dataList) && obj.dataList.length > 0) {
    for (let i = 0; i < obj.dataList.length; i++) {
      if (obj.dataList[i][obj.value] == obj.data) {
        color = obj.dataList[i][obj.label];
      }
    }
  }
  return {
    color: color,
  };
};

		//躺平计算小玩意
        // 存款计算函数 单位元
        // money 现有存款 
        // monthmoney 每月预计花销
        // month 花费的月份时间
        // rateofinterest 存款年化率
        // remainingsum 剩余金额
        let remainingsum = ''
        function Depositcalculation (money, monthmoney, month, rateofinterest) {
            for (var i = 1; i < month; i++) {
                remainingsum = (money + (money * rateofinterest / 100 / 12) - monthmoney)
                money = remainingsum
            }
            let a = `本金${money / 10000}万元,年化利率${rateofinterest}%,每月花销${monthmoney}元,经过${month}个月的花费(${month / 12}年),还有余额${remainingsum / 10000}万元`
            return console.log(a);
        }

        Depositcalculation(1000000, 2000, 12, 2.5)
        Depositcalculation(1000000, 2000, 120, 2.5)
        Depositcalculation(1000000, 2000, 240, 2.5)
        Depositcalculation(1000000, 2000, 360, 2.5)
        Depositcalculation(1000000, 2000, 480, 2.5)



// 获取最近10年
export const getyearList = () => {
  let thisyear = new Date().getFullYear()
  let arr = []
  for (var i = 0; i < 10; i++) {
    arr.push({
      label: `${thisyear - i}`,
      value: thisyear - i,
    })
  }
  return arr
}

export const yearList = getyearList()

let arr = ['18月''8月’,'9]
let newarr = arr.map((item, index) => {return {
name: item,
index: index
newname: Number(item.replace(/[ @-9]/ig,
1)
var compare = function (prop) freturn function (obj1, obj2) {var val1 = obj1[prop];
var val2 = obj2[prop]; if (val1 < val2) {
return -1;
else if (val1 > val2)
return 1:
else {
return 8;
var result = function (arr) flet a = arr.map(item => [
return item.name
return a
console.log(newarr .sort(compare('newname')));console.log(arr,result(newarr));```

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值