转时间-数组处理等


export default {
  getOnlyID (length = 10) {
    return Number(Math.random().toString().substr(3, length) + Date.now()).toString(36);
  },
  isHaveChart_CN(value){
     let is = false
    let cnPattern = new RegExp("/.*[\u4e00-\u9fa5]+.*$/");
    
    if(cnPattern.test(value)){
      is = true
    }
    return is
  },

  // 获取数组维度
  // let arr = [1,2,[3,4,5],[6,7,8,9,10,[11,12,[13]]]]
  // getDeepth(arr) ====》 4
  getDeepth(array) {
    function sum(arr, flag) {
      return arr.reduce(function (total, item) {
        var totalDeepth;
        if (Array.isArray(item)) {
          totalDeepth = sum(item, flag + 1);
        }
        return totalDeepth > total ? totalDeepth : total;
      }, flag)
    }
    return sum(array, 1);
  },
  // 将普通function转为promise方法
  // .eg1:
  //   mgr.readFile(filePath,successCallback,errorCallback, isText)
  // 转换后
  //   promisify(readFile,[filePath,Promise,isText],mgr)
  //     .then(....)
  //     .catch(...)
  // .eg2:
  // readFile(successCallback,errorCallback,filePath,isText)
  // 转换后
  //     promisify(readFile,[filePath,isText])
  //     .then(....)
  //     .catch(...)

  // Base64 to Blob
  // 调用:let base64 = base64.split(',')[1]
  // base64ToBlob({b64data: base64, contentType: 'image/png'}).then(res => {
  //   // 转后后的blob对象
  //   console.log('blob', res)
  // })
  base64ToBlob({ b64data = '', contentType = '', sliceSize = 512 } = {}) {
    return new Promise((resolve, reject) => {
      // 使用 atob() 方法将数据解码
      let byteCharacters = atob(b64data);
      let byteArrays = [];
      for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
        let slice = byteCharacters.slice(offset, offset + sliceSize);
        let byteNumbers = [];
        for (let i = 0; i < slice.length; i++) {
          byteNumbers.push(slice.charCodeAt(i));
        }
        // 8 位无符号整数值的类型化数组。内容将初始化为 0。
        // 如果无法分配请求数目的字节,则将引发异常。
        byteArrays.push(new Uint8Array(byteNumbers));
      }
      let result = new Blob(byteArrays, {
        type: contentType
      })
      result = Object.assign(result, {
        // 这里一定要处理一下 URL.createObjectURL
        preview: URL.createObjectURL(result),
        name: `XXX.png`
      });
      resolve(result)
    })
  },
  // Blob to Base64
  // 调用:blobToBase64(blob).then(res => {
  //   // 转化后的base64
  //   console.log('base64', res)
  // })
  blobToBase64(blob) {
    return new Promise((resolve, reject) => {
      const fileReader = new FileReader();
      fileReader.onload = (e) => {
        resolve(e.target.result);
      };
      // readAsDataURL
      fileReader.readAsDataURL(blob);
      fileReader.onerror = () => {
        reject(new Error('blobToBase64 error'));
      };
    });
  },
  // 本地图片转base64
  getBase64 (url) {
    const base64Regex = /^data:image\/(png|jpg|svg|svg\+xml);base64,/;
    if (base64Regex.test(url)) {
      return url;
    } else {
      return new Promise((resolve, reject) => {
        var Img = new Image();
        var dataURL = '';
        Img.setAttribute('crossOrigin', 'Anonymous');
        Img.src = url;
        try {
          Img.onload = function () {
            // 要先确保图片完整获取到,这是个异步事件
            var canvas = document.createElement('canvas'); // 创建canvas元素
            var width = Img.width; // 确保canvas的尺寸和图片一样
            var height = Img.height;
            canvas.width = width;
            canvas.height = height;
            canvas.getContext('2d').drawImage(Img, 0, 0, width, height); // 将图片绘制到canvas中
            dataURL = canvas.toDataURL('image/png'); // 转换图片为dataURL
            resolve(dataURL);
          };
          Img.onerror = (err) =>{
            resolve(dataURL);
          }
        } catch (err) {
          if (dataURL === '') {
            this.$popmessage('error', '请移除空图!');
          }
          resolve(dataURL);
        }
      });
    }
  },
  // 给图片加图片水印
  async fillImgToImg(base64, waterMark = '', width = 24, height = 24) {
    const img = new Image();
    img.src = base64;
    img.setAttribute("crossOrigin", "Anonymous");
    return new Promise((resolve, reject) => {
      img.onload = async () => {
        const canvas = document.createElement("canvas");
        const ctx = canvas.getContext("2d");
        // ctx.fillStyle = '#fff' // canvas背景填充颜色默认为黑色
        canvas.width = img.width;
        canvas.height = img.height;
        ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
        const waterMarkSrc = await this.getBase64(waterMark, 100); 
        const waterMarkImg = new Image();
        waterMarkImg.src = waterMarkSrc;
        waterMarkImg.setAttribute("crossOrigin", "Anonymous");
        waterMarkImg.onload = () => {
          ctx.drawImage(
            waterMarkImg,
            canvas.width - width,
            0,
            width,
            height
          );
          resolve(canvas.toDataURL("image/png"));
        };
      };
    }).catch(e=>{
      console.log('水印err',e)
    });
  },
  // 判断是对象还是数组
  isObjArr(value){
    if (Object.prototype.toString.call(value) === "[object Array]") {
      return 'arr';
      }else if(Object.prototype.toString.call(value)==='[object Object]'){
      return 'obj';
    }else{
      return 'none';
    }
  },
  //对象数组排序
  sortByKey(array, key) {
    return array.sort(function (a, b) {
      var x = a[key];
      var y = b[key];
      return ((x < y) ? -1 : ((x > y) ? 1 : 0));
    })
  },

  //数组按指定长度分割
  group(array, subGroupLength) {
    let index = 0;
    let newArray = [];
    while (index < array.length) {
      newArray.push(array.slice(index, index += subGroupLength));
    }
    return newArray;
  },
  getRandomColor(Rrang, Grang, Brang, opacity, Listlength, type) {
    let colorList = []
    for (let i = 0; i < Listlength; i++) {
      var r, g, b, a = ''
      if (Array.isArray(Rrang)) {
        r = Math.floor((Math.random() * (Rrang[1] - Rrang[0] + 1)) + Rrang[0]);
      } else {
        r = Math.floor(Math.random() * 256);
      }
      if (Array.isArray(Grang)) {
        g = Math.floor((Math.random() * (Grang[1] - Grang[0] + 1)) + Grang[0]);
      } else {
        g = Math.floor(Math.random() * 256);
      }
      if (Array.isArray(Brang)) {
        b = Math.floor((Math.random() * (Brang[1] - Brang[0] + 1)) + Brang[0]);
      } else {
        b = Math.floor(Math.random() * 256);
      }
      if (type === 'color16') {
        colorList.push("#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1))
      } else if (type === 'rgba') {
        //rgb颜色随机
        colorList.push('rgba(' + r + ',' + g + ',' + b + ',' + opacity + ')');
      } else if (type === 'rgb') {
        //rgb颜色随机
        colorList.push('rgb(' + r + ',' + g + ',' + b + ')');
      }
    }
    return colorList;
  },
  renderSize(value) {
    if (value === null || value === '' || value === 0) {
      return '0 KB';
    }
    var unitArr = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
    var index = 0;
    var srcsize = parseFloat(value);
    srcsize = srcsize < 1024 ? 1024 : srcsize;
    index = Math.floor(Math.log(srcsize) / Math.log(1024));
    var size = srcsize / Math.pow(1024, index);
    //  保留的小数位数
    if (unitArr[index] === 'Bytes') {
      size = parseInt(size)
    } else {
      size = size.toFixed(2);
    }


    return size + unitArr[index];
  },
  promisify(method, params, scope) {
    let index = params.indexOf(Promise);
    if (index < 0) {
      index = 0;
    }
    return new Promise((resolve, reject) => {
      params.splice(index, 1, resolve, reject);
      method.apply(scope, params);
    });
  },
  // 判断空对象
  isEmptyObject(obj) {
    for (var key in obj) {
      return false;
    }
    return true;
  },
  // checkImg (imgurl) {
  //   var p = new Promise(function (resolve, reject) {
  //     var ImgObj = new Image(); // 判断图片是否存在
  //     ImgObj.src = imgurl;
  //     // 没有图片,则返回-1
  //     if (ImgObj.fileSize > 0 || (ImgObj.width > 0 && ImgObj.height > 0)) {
  //       resolve(true);
  //     } else {
  //       reject(false);
  //     }
  //   });
  //   return p;
  // },
  // 验证图片资源是否存在(404)
  checkImgExists(imgurl) {
    var ImgObj = new Image(); // 判断图片是否存在
    ImgObj.src = imgurl;
    // 没有图片,则返回-1
    if (ImgObj.fileSize > 0 || (ImgObj.width > 0 && ImgObj.height > 0)) {
      return true;
    } else {
      return false;
    }
  },
  // 在数组1(arr)中移除数组2(brr)包含的元素
  // e.g :
  // var arr = [1, 2, 3, 4, '1', 0,  1, 2, 'a', 'b','d'];
  // var brr = [1, 2, 'a','c'];
  // console.log(temparray); ===> [3, 4, "1", 0, "b", "d"]
  removeArrayInArray(arr, brr) {
    var temp = [];
    var temparray = [];
    for (let i = 0; i < brr.length; i++) {
      temp[brr[i]] = typeof brr[i];
    }
    for (let i = 0; i < arr.length; i++) {
      var type = typeof arr[i];
      if (!temp[arr[i]]) {
        temparray.push(arr[i]);
      } else if (temp[arr[i]].indexOf(type) < 0) {
        temparray.push(arr[i]);
      }
    }
  },
  removeArrayInArray1(arr, brr) {
    var temp = [];
    var temparray = [];
    for (let i = 0; i < brr.length; i++) {
      temp[brr[i]] = typeof brr[i];
    }
    for (let i = 0; i < arr.length; i++) {
      var type = typeof arr[i];
      if (!temp[arr[i]]) {
        temparray.push(arr[i]);
      } else if (temp[arr[i]].indexOf(type) < 0) {
        temparray.push(arr[i]);
      }
    }
    return temparray;
  },
  // 两数组交集
  intersect(arr1, arr2) {
    if (Object.prototype.toString.call(arr1) === '[object Array]' && Object.prototype.toString.call(arr2) === '[object Array]') {
      return arr1.filter(function (v) {
        return arr2.indexOf(v) !== -1;
      });
    }
  },
  // 两数组并集
  union(arr1, arr2) {
    if (Object.prototype.toString.call(arr1) === '[object Array]' && Object.prototype.toString.call(arr2) === '[object Array]') {
      return this.unique(arr1.concat(arr2));
    }
  },
  // 两数组合并
  hebing(resarr, hebingarr) {
    resarr = resarr.concat(hebingarr);
    return resarr;
  },
  // 判断数组中是否包含某元素(searchvalue,fromindex)
  ifInArr(searchvalue, fromindex) {
    return !(fromindex.indexOf(searchvalue) < 0);
  },
  // 数组去重
  unique(arr) {
    var res = [];
    var json = {};
    for (var i = 0; i < arr.length; i++) {
      if (!json[arr[i]]) {
        res.push(arr[i]);
        json[arr[i]] = 1;
      }
    }
    return res;
  },
  // 二维数组去重
  uniqueTwo(arr) {
    const obj = {};
    arr.forEach(item => !obj[item.toString()] && (obj[item.toString()] = item));
    return Object.values(obj);
  },
  // 数组根据对象的某个属性值去重
  uniqueObj(arr, key) {
    const res = new Map();
    return arr.filter((item) => !res.has(item[key]) && res.set(item[key], 1));
  },
  // 两数组不同元素
  diff(arr1, arr2) {
    var newArr = [];
    var arr3 = [];
    for (var i = 0; i < arr1.length; i++) {
      if (arr2.indexOf(arr1[i]) === -1) { arr3.push(arr1[i]); }
    }
    var arr4 = [];
    for (var j = 0; j < arr2.length; j++) {
      if (arr1.indexOf(arr2[j]) === -1) { arr4.push(arr2[j]); }
    }
    newArr = arr3.concat(arr4);
    return newArr;
  },

  // 判断某对象属性是否存在且为非空字符串,若是则返回true,否为返回false
  ishasValue(pro) {
    if (pro === '') {
      return false;
    } else {
      return true;
    }
  },

  mergeArray(arr1, arr2){
    let arr = arr1;
    arr2.forEach(item => {
      if(arr.indexOf(item) === -1){
        arr.push(item)
      }
    })
    return arr
  },

  // 判断item是否存在于arr数组中,若存在,则返回第一个位置,若不存在,则返回-1
  itemIndexInArr(item, arr) {
    if (arr.length > 0) {
      for (var i = 0; i < arr.length; i++) {
        if (item === arr[i]) {
          return i;
        }
        if (i === arr.length - 1) {
          return -1;
        }
      }
    } else {
      return -1;
    }
  },
  // 获取当前日期
  getNowFormatDate() {
    var date = new Date();
    var seperator1 = '-';
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
      month = '0' + month;
    }
    if (strDate >= 0 && strDate <= 9) {
      strDate = '0' + strDate;
    }
    var currentdate = year + seperator1 + month + seperator1 + strDate;
    return currentdate;
  },
  //获取当前日期--到分
  getCurentTime() {
    var now = new Date();
    var year = now.getFullYear();// 年
    var month = now.getMonth() + 1;// 月
    var day = now.getDate();// 日
    var hh = now.getHours();// 时
    var mm = now.getMinutes();// 分
    var ss = now.getSeconds();
    var clock = year + '-';
    if (month < 10) { clock += '0'; }
    clock += month + '-';
    if (day < 10) { clock += '0'; }
    clock += day + ' ';
    if (hh < 10) { clock += '0'; }
    clock += hh + ':';
    if (mm < 10) clock += '0';
    clock += mm + ':';
    if (ss < 10) clock += '0';
    clock += ss ;
    return clock;
  },
  //获取当前日期--到分
  getTimeHMS() {
    var now = new Date();
    var hh = now.getHours();// 时
    var mm = now.getMinutes();// 分
    var ss = now.getSeconds();
    var clock = '';
    if (hh < 10) { clock += '0'; }
    clock += hh + ':';
    if (mm < 10) clock += '0';
    clock += mm + ':';
    if (ss < 10) clock += '0';
    clock += ss ;
    return clock;
  },
  // 过去一天的时间
  getPassDayFormatDate() {
    var nowDate = new Date();
    var date = new Date(nowDate);
    date.setDate(date.getDate() - 1);
    var seperator1 = '-';
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
      month = '0' + month;
    }
    if (strDate >= 0 && strDate <= 9) {
      strDate = '0' + strDate;
    }
    var currentdate = year + seperator1 + month + seperator1 + strDate;
    return currentdate;
  },
  // 过去一周的时间
  getPassWeekFormatDate() {
    var nowDate = new Date();
    var date = new Date(nowDate);
    date.setDate(date.getDate() - 7);
    var seperator1 = '-';
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
      month = '0' + month;
    }
    if (strDate >= 0 && strDate <= 9) {
      strDate = '0' + strDate;
    }
    var currentdate = year + seperator1 + month + seperator1 + strDate;
    return currentdate;
  },
  // 过去n个月的时间
  getPassMonthFormatDate(n = 1) {
    var nowDate = new Date();
    var date = new Date(nowDate);
    date.setDate(date.getDate() - (30 * n));
    var seperator1 = '-';
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
      month = '0' + month;
    }
    if (strDate >= 0 && strDate <= 9) {
      strDate = '0' + strDate;
    }
    var currentdate = year + seperator1 + month + seperator1 + strDate;
    return currentdate;
  },
  // 过去一年的时间
  getPassYearFormatDate() {
    var nowDate = new Date();
    var date = new Date(nowDate);
    date.setDate(date.getDate() - 365);
    var seperator1 = '-';
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
      month = '0' + month;
    }
    if (strDate >= 0 && strDate <= 9) {
      strDate = '0' + strDate;
    }
    var currentdate = year + seperator1 + month + seperator1 + strDate;
    return currentdate;
  },
  // date yy-mm-dd 转 时间戳 (秒)
  getTimestamp(time) {
    return Date.parse(new Date(time)) / 1000;
  },
  // date yy-mm-dd 转 时间戳 (毫秒)
  getTimestampMS(time) {
    return Date.parse(new Date(time));
  },
  // date yy-mm-dd 转 时间戳 该天凌晨(毫秒)
  getTimestampMorning(n){
    return new Date(n).setHours(0,0,0,0);
  },
  // date yy-mm-dd 转 时间戳  该天夜晚凌晨(毫秒)
  getTimestampNight(n){
    return new Date(n).setHours(23,59,59,59);
  },
  // 时间戳转(毫秒) yy-mm-dd
  transformPHPTimeMS(time) {
    var date = new Date(time * 1000);
    const Y = date.getFullYear() + '-';
    const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    const D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate());
    return Y + M + D;
  },
  // 时间戳转(毫秒) yy-mm-dd
  transformTimeMS(time) {
    var date = time ? time : new Date();
    const Y = date.getFullYear() + '-';
    const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    const D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate());
    const space = ' ';
    const h = date.getHours() + ':';
    const m = date.getMinutes() + ':';
    const s = date.getSeconds();
    return Y + M + D + space + h + m + s;
  },
  // 时间戳转(秒) yy-mm-dd
  transformPHPTime(time) {
    var date = new Date(time)
    var y = date.getFullYear()
    var m = date.getMonth() + 1
    m = m < 10 ? ('0' + m) : m
    var d = date.getDate()
    d = d < 10 ? ('0' + d) : d
    return y + '-' + m + '-' + d
  },


  // ivew时间选择器--转换为yy-mm-dd
  getDate(dtStr) {
    if(dtStr === '' || !dtStr) return '';
    let dt = new Date(Date.parse(dtStr))
    let ms = dt.getMonth() + 1
    if (ms < 10) ms = '0' + ms;
    let ds = dt.getDate();
    if (ds < 10) ds = '0' + ds;
    return `${dt.getFullYear()}-${ms}-${ds}`
  },
  // ivew时间选择器--转换为yy-mm-dd
  getDateRange(dr) {
    if (dr.length > 0 && dr[0]) {
      return [this.getDate(dr[0]), this.getDate(dr[1])];
    }
    return []
  },

  getTimeDifference (date1, text = '') {
    // var date1= '2015/05/01 00:00:00';  //开始时间
    var date2 = new Date();    //结束时间
    var date3 = date2.getTime() - new Date(date1).getTime();   //时间差的毫秒数      
    //计算出相差天数
    var days=Math.floor(date3/(24*3600*1000))
    //计算出小时数
    var leave1=date3%(24*3600*1000)    //计算天数后剩余的毫秒数
    var hours=Math.floor(leave1/(3600*1000))
    //计算相差分钟数
    var leave2=leave1%(3600*1000)        //计算小时数后剩余的毫秒数
    var minutes=Math.floor(leave2/(60*1000))
    //计算相差秒数
    var leave3=leave2%(60*1000)      //计算分钟数后剩余的毫秒数
    var seconds=Math.round(leave3/1000)
    // alert(" 相差 "+days+"天 "+hours+"小时 "+minutes+" 分钟"+seconds+" 秒")
    if(days > 0) {
      if(days > 7) {
        const time = this.getDate(date1)
        return time
      } else {
        return `${text}${days}天前`
      }
    } else if(hours > 0) {
      return `${text}${hours}小时前`
    } else if(minutes > 0) {
      return `${text}${minutes}分钟前`
    } else if(seconds > 0) {
      return `${text}${seconds}秒前`
    } else if(seconds === 0) {
      return `${text}1秒前`
    }else {
      return ''
    }
  },
  // 树形递归遍历
  traverseNode(node) {
    // console.log('----node-----')
    // console.log(node)
  },
  traverseTree(node) {
    if (!node) {
      return;
    }
    // traverseNode(node);
    if (node.children && node.children.length > 0) {
      var i = 0;
      for (i = 0; i < node.children.length; i++) {
        this.traverseTree(node.children[i]);
      }
    }
  },
  // 非递归遍历
  traverseNode2(node) {
    // console.log('------')
    // console.log(node)
    // console.log('------')
  },
  traverseTree2(node) {
    if (!node) {
      return;
    }

    var stack = [];
    stack.push(node);
    var tmpNode;
    while (stack.length > 0) {
      tmpNode = stack.pop();
      this.traverseNode2(tmpNode);
      if (tmpNode.children && tmpNode.children.length > 0) {
        var i = tmpNode.children.length - 1;
        for (i = tmpNode.children.length - 1; i >= 0; i--) {
          stack.push(tmpNode.children[i]);
        }
      }
    }
  },
  // 写入本地存储
  writeStorage(name, ids) {
    sessionStorage.setItem(name, JSON.stringify(ids));
  },
  getStorage(name, index) {
    var idArr = JSON.parse(sessionStorage.getItem(name));
    if (Array.isArray(index)) {
      if (index[0] === index[1]) {
        let useIds = idArr[index[0]];
        const reUseIds = [];
        useIds = useIds.filter(item => item.length > 0);
        reUseIds.push(useIds);
        return reUseIds;
      } else {
        let useIds = idArr.slice(index[0], index[1] + 1);
        useIds = useIds.filter(item => item.length > 0);
        return useIds;
      }
    } else {
      return idArr[index];
    }
  },
  removeStorage(name) {
    sessionStorage.removeItem(name);
  },
  // 对象深克隆
  deepClone(obj) {
    const _obj = JSON.stringify(obj);
    const objClone = JSON.parse(_obj);
    return objClone;
  },
  getMaxMin(arr) {
    var max = arr[0];
    var min = arr[0];
    for (var i = 0; i < arr.length; i++) {
      if (max < arr[i]) {
        max = arr[i]
      }
      if (min > arr[i]) {
        min = arr[i]
      }

    }
    let reqArr = [max, min];
    return reqArr
  },


  //获取多元数组中最底层子节点个数
  getChildNum(jsonArr) {
    if (jsonArr.constructor === Array) {
      return this.countFunction(0, jsonArr);
    } else {
      return 0;
    }
  },
  countFunction(startNum, jsonArr) {
    // jsonArr.forEach(item => {
    //   if (item===undefined||item===null || item.constructor !== Array) {
    //     startNum++;
    //   } else {
    //     startNum = startNum + this.countFunction(0, item);
    //   }
    // });
    for (let i = 0; i < jsonArr.length; i++) {
      if (jsonArr[i] === undefined || jsonArr[i] === null || jsonArr[i] === '' || jsonArr[i].constructor !== Array) {
        startNum++;
      } else {
        startNum = startNum + this.countFunction(0, jsonArr[i]);
      }
    }
    return startNum;
  },

  //获取多元数组中最底层子节点
  getChildren(jsonArr) {
    if (jsonArr.constructor === Array) {
      return this.childFunction([], jsonArr);
    } else {
      return 0;
    }
  },
  childFunction(startArr, jsonArr) {
    for (let i = 0; i < jsonArr.length; i++) {
      if (jsonArr[i] === undefined || jsonArr[i] === null || jsonArr[i] === '' || jsonArr[i].constructor !== Array) {
        startArr.push(jsonArr[i]);
      } else {
        startArr = startArr.concat(this.childFunction([], jsonArr[i]));
      }
    }
    return startArr;
  },

  //获取渐进颜色
  shadeColor(startColor, endColor, step) {
    var startRGB = this.colorRgb(startColor);//转换为rgb数组模式
    var startR = startRGB[0];
    var startG = startRGB[1];
    var startB = startRGB[2];

    var endRGB = this.colorRgb(endColor);
    var endR = endRGB[0];
    var endG = endRGB[1];
    var endB = endRGB[2];

    var sR = (endR - startR) / step;//总差值
    var sG = (endG - startG) / step;
    var sB = (endB - startB) / step;

    var colorArr = [];
    for (var i = 0; i < step; i++) {
      //计算每一步的hex值 
      var hex = this.colorHex('rgb(' + parseInt((sR * i + startR)) + ',' + parseInt((sG * i + startG)) + ',' + parseInt((sB * i + startB)) + ')');
      colorArr.push(hex);
    }
    return colorArr;
  },
  //数字改变(整合数字,按位数加千\万)
  figureChange(param) {
    let num = parseFloat(param)
    if ( num && num.toString() !== "NaN") {
      return (num>=10000)?((num / 10000).toFixed(1) + 'W'):(num>=1000?((num / 1000).toFixed(1) + 'K'):(num+''));
    } else {
      console.log('---------figureChange--------------',param)
      return param||0;
    }
  },

  isObjectValueEqual(a, b) {
    var aProps = Object.getOwnPropertyNames(a);
    var bProps = Object.getOwnPropertyNames(b);
    if (aProps.length != bProps.length) {
      return false;
    }
    for (var i = 0; i < aProps.length; i++) {
      var propName = aProps[i]

      var propA = a[propName]
      var propB = b[propName]
      if ((typeof (propA) === 'object')) {
        if (this.isObjectValueEqual(propA, propB)) {
          return true
        } else {
          return false
        }
      } else if (propA !== propB) {
        return false
      } else { }
    }
    return true
  },
  eq(a, b) {
    if (a === b) return a !== 0 || 1 / a === 1 / b;
    if (a == null || b == null) return false;
    if (a !== a) return b !== b;
    var type = typeof a;
    if (type !== 'function' && type !== 'object' && typeof b != 'object') return false;
    return this.isObjectValueEqual(a, b)
  },
  // 防抖
  _debounce(fn, delay) {
    delay = delay || 200;
    // var timer;
    return function () {
      var th = this;
      var args = arguments;
      if (timer) {
        console.log(timer)
        clearTimeout(timer);
      }
      var timer = setTimeout(function () {
        timer = null;
        fn.apply(th, args);
      }, delay);
    };
  },
  debounce(func, wait=0) {    
   if (typeof func !== 'function') {
    throw new TypeError('need a function arguments')
   }
   let timeid = null;
      let result;
  
   return function() {
    let context = this;
    let args = arguments;
    if (timeid) {
      clearTimeout(timeid);
    }
    timeid = setTimeout(function() {
      result = func.apply(context, args);
    }, wait);
  
    return result;
   }
  },
  // 节流
  _throttle(fn, interval) {
    var last;
    var timer;
    var interval = interval || 200;
    return function () {
      var th = this;
      var args = arguments;
      var now = +new Date();
      if (last && now - last < interval) {
        clearTimeout(timer);
        timer = setTimeout(function () {
          last = now;
          fn.apply(th, args);
        }, interval);
      } else {
        last = now;
        fn.apply(th, args);
      }
    }
  },
  // 判断-一维数组-相等
  arrayEqual (arr1, arr2) {
    if (arr1.length !== arr2.length) return false;
    for (var i = 0; i < arr1.length; ++i) {
        if (arr1[i] !== arr2[i]) return false;
    }
    return true;
  },
  //判断-json-全等
  compare(objA, objB) {
    if (!this.isObj(objA) || !this.isObj(objB)) return false; //判断类型是否正确
    if (this.getLength(objA) != this.getLength(objB)) return false; //判断长度是否一致
    return this.compareObj(objA, objB, true);//默认为true
  },
  isObj(object) {
    return object && typeof (object) == 'object' && Object.prototype.toString.call(object).toLowerCase() == "[object object]";
  },
  isArray(object) {
    return object && typeof (object) == 'object' && object.constructor == Array;
  },
  isString(str) { 
    return (typeof str == 'string') && str.constructor == String
  },
  getLength(object) {
    var count = 0;
    for (var i in object) count++;
    return count;
  },
  compareObj(objA, objB, flag) {
    for (var key in objA) {
      if (!flag) //跳出整个循环
        break;
      if (!objB.hasOwnProperty(key)) { flag = false; break; }
      if (!this.isArray(objA[key])) { //子级不是数组时,比较属性值
        if (objB[key] != objA[key]) { flag = false; break; }
      } else {
        if (!this.isArray(objB[key])) { flag = false; break; }
        var oA = objA[key], oB = objB[key];
        if (oA.length != oB.length) { flag = false; break; }
        for (var k in oA) {
          if (!flag) //这里跳出循环是为了不让递归继续
            break;
          flag = this.compareObj(oA[k], oB[k], flag);
        }
      }
    }
    return flag;
  },
  // 判断对象是否为空
  isEmptyObj(obj) {
    for (let k in obj) {
      return false
    }
    return true
  },

  //强制限制只能输入数字
  checkInt(value) {
    var t = value.charAt(0);
    value = value.replace(/[^\d]/g, "");  //清除“数字”的字符
    if (value !== "") {//以上已经过滤,此处控制的是如果没有小数点,首位不能为类似于 01、02的金额
      value = parseInt(value).toString();
    }
    if (t === '-') {
      value = '-' + value;
    }
    return value
  },
  checkFloat(value) {
    value = value.toString()
    var t = value.charAt(0);
    value = value.replace(/[^\d.]/g, "");  //清除“数字”和“.”以外的字符
    value = value.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的
    value = value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
    let index = value.indexOf('.')
    if (index < 0 && value !== "") {//以上已经过滤,此处控制的是如果没有小数点,首位不能为类似于 01、02的金额
      value = parseFloat(value).toString();
    }
    // if(index < 0){}
    if (t === '-') {
      value = '-' + value;
    }
    return value
  },
  floatAddZero(value) {
    let index = value.indexOf('.')
    if (index < 0 && value !== "") {
      value += '.000001'
    }
    return value
  },
  //获取属性结构的某级别内的数据
  // 获取N级及以上的树型结构
  getAllChildrenByLevel (arr, levelNum, maxLevelNum) {
    var getChildren = function (arr, levelNum, maxLevelNum) {
      arr.forEach((item) => {
        if (levelNum > maxLevelNum - 1) {
          item.children = undefined;
        } else {
          if (item.children && item.children.length > 0) {
            const tempNum = levelNum + 1;
            getChildren(item.children, tempNum, maxLevelNum);
          } else {
            item.children = undefined;
          }
        }
      });
    };
    getChildren(arr, levelNum, maxLevelNum);
    return arr;
  },
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值