JS常用功能实现

最新更新: 2020-08-08 17:31:23 阅读: 43次

1、对象方式实现数组去重(数组里有对象)

arrayUnique = (arr, name) => {
  var hash = {};
  return arr.reduce(function (item, next) {
    hash[next[name]] ? "" : (hash[next[name]] = true && item.push(next));
    return item;
  }, []);
};
2、求差集(数组)

diffrence = (a, b, name) => {
      a = a.map(JSON.stringify);
      b = b.map(JSON.stringify);
      return a
        .concat(b)
        .filter((v) => {
          let val1 = name ? v[name] : v;
          return !a.includes(val1) || !b.includes(val1)
        })
        .map(JSON.parse);
    }
3、获取当天是星期几

getWeek = (time) => {
      return "星期" + "日一二三四五六".charAt(new Date(time).getDay());
 };
4、获取当前时间的周一和周日

getMonSun = (val) => {
      var now = val ? new Date(val) : new Date();
      var nowTime = now.getTime();
      var day = now.getDay();
      var oneDayTime = 24 * 60 * 60 * 1000;
      return {
        Mon: nowTime - (7 - day) * oneDayTime,
        Sun: nowTime + (7 - day) * oneDayTime,
      };
 };
5、数组排序(借助sort)

arrObjSort = (prop, isDate) => {
      return function (obj1, obj2) {
        var val1 = obj1[prop];
        var val2 = obj2[prop];
         if (!isNaN(Number(val1)) && !isNaN(Number(val2))) {
          val1 = Number(val1);
          val2 = Number(val2);
        }
        if (val1 < val2) {
          return -1;
        } else if (val1 > val2) {
          return 1;
        } else {
          return 0;
        }
      };
    };
6、时间格式化

rotateTime = (inputTime,  format) => {
      if (!inputTime) return;
      //将格式-转为/,浏览器兼容
      if (typeof inputTime === "string") {
        inputTime = inputTime.replace(/-/g, "/");
      }
      var date = new Date(inputTime);
      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;
      var h = date.getHours();
      h = h < 10 ? "0" + h : h;
      var minute = date.getMinutes();
      var second = date.getSeconds();
      minute = minute < 10 ? "0" + minute : minute;
      second = second < 10 ? "0" + second : second;
      if (format) {
        //用变量名的值替换掉字符串字母
        [{
            name: 'y',
            val: y
          }, {
            name: 'm',
            val: m
          }, {
            name: 'd',
            val: d
          },
          {
            name: 'h',
            val: h
          }, {
            name: 'minute',
            val: minute
          },
          {
            name: 'second',
            val: second
          }
        ].forEach(a => {
          format = format.replace(new RegExp(a.name, 'i'), a.val)
        })
        return format
      } else {
        return y + "-" + m + "-" + d;
      }
    };
7、获取当月第一天

getCurrentMonthFirst = (val) => {
      var date = val ? new Date(val) : new Date();
      date.setDate(1);
      return date;
    };
8、获取当月最后一天

getCurrentMonthLast = (val) => {
      var date = val ? new Date(val) : new Date();
      var currentMonth = date.getMonth();
      var nextMonth = ++currentMonth;
      var nextMonthFirstDay = new Date(date.getFullYear(), nextMonth, 1);
      var oneDay = 1000 * 60 * 60 * 24;
      return new Date(nextMonthFirstDay - oneDay);
    };
9、去字符串左右空格

toTrim = (str) => {
      if (String.prototype.trim) {
        return str.trim();
      }
      return str.replace(/^s+(.*?)s+$/g, "$1");
    };
10、防抖

_debounce = (fn, delay) => {
  var delay = delay || 400;
  var timer;

  return function () {
    var th = this;
    var args = arguments;
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(function () {
      timer = null;
      fn.apply(th, args);
    }, delay);
  };
}
11、节流

_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);
    }
  };
};
12、判断数据类型

type = (obj) => {
  // console.log('global..:', 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",
  };
  return map[toString.call(obj)];
};
13、数组或对象深拷贝

deepCopy = (data) => {
  //console.log('deepCopy..:', data)
  var t = type(data),
    o,
    i,
    ni;
  if (t === "array") {
    o = [];
  } else if (t === "object") {
    o = {};
  } else {
    return data;
  }
  if (t === "array") {
    for (i = 0, ni = data.length; i < ni; i++) {
      o.push(deepCopy(data[i]));
    }
    return o;
  } else if (t === "object") {
    for (i in data) {
      o[i] = deepCopy(data[i]);
    }
    return o;
  }
};
14、获取当前时间是今年第几周

 //今年的第几周
   getWeek1(val) {
     let date = val ? new Date(val) : new Date() ;
     let this_year=date.getFullYear()
     //今年的第一个周日算起
     let y=this.getMonSun(new Date(this_year,0,1)).Sun ;//今年第一周结束时间
     let curT=date.getTime();
     let week='';
     if(curT<y){
       //在第一周内
       week=1
     }else {
       let start=y+24 * 60 * 60 * 1000 //今年第二周的周一开始时间
       let d= Math.round(curT - start)/86400000 ; //从第二周开始的今年第几天
       week=Math.ceil((d) / 7)+1
     }
     return { y: this_year, w: week }
   },