js公共方法

import {MessageBox, Message} from 'element-ui'
// 1.验证手机号是否合格
// true  合格
export function isPhone(phoneStr) {
  let myreg = /^[1][3,4,5,7,8,9][0-9]{9}$/;
  if (!myreg.test(phoneStr)) {
    return false;
  } else {
    return true;
  }
}

// 2.验证身份证号是否合格
// true 说明合格
export function isIdCard(idCardStr) {
  let idcardReg = /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/;
  if (idcardReg.test(idCardStr)) {
    return true;
  } else {
    return false;
  }
}

// 3.验证字符串是否为空
// ture 说明为空  false 说明不为空
export function isEmptyString(string) {
  if (
    string == undefined ||
    typeof string == 'undefined' ||
    !string ||
    string == null ||
    string == '' ||
    /^\s+$/gi.test(string)
  ) {
    return true;
  } else {
    return false;
  }
}

// 4.判断数据类型
/* @param {any} val - 基本类型数据或者引用类型数据
* @return {string} - 可能返回的结果有,均为小写字符串
* number、boolean、string、null、undefined、array、object、function等
*/
export function getType(val) {
  //判断数据是 null 和 undefined 的情况
  if (val == null) {
    return val + "";
  }
  return typeof (val) === "object" ?
    Object.prototype.toString.call(val).slice(8, -1).toLowerCase() :
    typeof (val);
}

// 5.验证是否为数字
export function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

// 6.是否为数组
export function isArray(obj) {
  return Object.prototype.toString.call(obj) === '[object Array]';
}

// 7.是否为空数组
export function isArrayEmpty(val) {
  if (val && val instanceof Array && val.length > 0) {
    return false;
  } else {
    return true;
  }
}

// 8.获取url参数字符串
// 没有返回null
export function getQueryString(name) {
  let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
  let r = window.location.search.substr(1).match(reg);
  if (r != null) {
    return unescape(r[2]);
  }
  return null;
}

// 9.函数防抖
/**
 * @desc  函数防抖,用于将多次执行变为最后一次执行
 * @param {function} func - 需要使用函数防抖的被执行的函数。必传
 * @param {Number} wait - 多少毫秒之内触发,只执行第一次,默认1000ms。可以不传
 */
export function debounce(fn, delay) {
  delay = delay || 1000; //默认1s后执行
  let timer = null;
  return function () {
    let context = this;
    let arg = arguments;
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      fn.apply(context, arg);
    }, delay);
  };
}

// 10.函数节流
/**
 * 节流函数, 用于将多次执行变为每隔一段时间执行
 * @param fn 事件触发的操作
 * @param delay 间隔多少毫秒需要触发一次事件
 */
export function throttle2(fn, delay) {
  let timer = null;
  return function () {
    let context = this;
    let args = arguments;
    if (!timer) {
      timer = setTimeout(function () {
        fn.apply(context, args);
        clearTimeout(timer);
      }, delay);
    }
  };
}

// 11.将字符串时间转换为时间戳
/**
 * 将字符串时间转换为时间戳
 * @param {string} date
 */
export function getDateTime(date) {
  let timestamp = '';
  if (date) {
    date = date.substring(0, 19);
    date = date.replace(/-/g, '/'); //必须把日期'-'转为'/'
    timestamp = new Date(date).getTime();
  }
  return timestamp;
}

// 12.获取年-月-日
/**
 * 获取年-月-日
 * @data {Any} 时间戳
 */
export function getDates(data) {
  let timeObj = {};
  data = new Date(data);
  let y = data.getFullYear();
  let m =
    data.getMonth() + 1 < 10
      ? '0' + (data.getMonth() + 1)
      : data.getMonth() + 1;
  let d = data.getDate() < 10 ? '0' + data.getDate() : data.getDate();
  let w = data.getDay();
  switch (w) {
    case 1:
      w = '星期一';
      break;
    case 2:
      w = '星期二';
      break;
    case 3:
      w = '星期三';
      break;
    case 4:
      w = '星期四';
      break;
    case 5:
      w = '星期五';
      break;
    case 6:
      w = '星期六';
      break;
    case 7:
      w = '星期日';
      break;
  }
  let h = data.getHours() < 10 ? '0' + data.getHours() : data.getHours();
  let mi = data.getMinutes() < 10 ? '0' + data.getMinutes() : data.getMinutes();
  let s = data.getSeconds() < 10 ? '0' + data.getSeconds() : data.getSeconds();
  timeObj = {
    year: y + '',
    month: m + '',
    day: d + '',
    week: w + '',
    hour: h + '',
    minute: mi + '',
    second: s + ''
  };
  return timeObj;
}

// 13.获取当前时间
/**
 * 获取当前时间
 * 使用
 * import { formatDate } from '@/src/utils/formatDate.js'
 * formatDate('YY')
 * formatDate('YY-MM')
 * formatDate('YY-MM-DD')
 * formatDate('YY-MM-DD hh:mm:ss')
 * formatDate('星期W')  // 星期一
 */
export const formatDate = (fmt) => {
  const date = new Date()
  const o = {
    'Y+': date.getFullYear(),
    'M+': date.getMonth() + 1, // 月
    'D+': date.getDate(), // 日
    'h+': date.getHours(), // 时
    'm+': date.getMinutes(), // 分
    's+': date.getSeconds(), // 秒
    W: date.getDay() // 周
  }
  for (let k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) {
      fmt = fmt.replace(RegExp.$1, () => {
        if (k === 'W') {
          // 星期几
          const week = ['日', '一', '二', '三', '四', '五', '六']
          return week[o[k]]
        } else if (k === 'Y+' || RegExp.$1.length === 1) {
          // 年份 or 小于10不加0
          return o[k]
        } else {
          return ('00' + o[k]).substr(('' + o[k]).length) // 小于10补位0
        }
      })
    }
  }
  return fmt
}

// 函数封装返回年月日时分秒
export function getTimer(data) {
  // 对象实例化
  var time = new Date();

  var year = time.getFullYear();
  // 1月到12月(0-11)
  var month = time.getMonth() + 1;
  var dates = time.getDate();

  // 周日-周六(0-6) 刚好对应数字下标
  var day = time.getDay();
  var arr = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
  var hours = time.getHours();
  var minutes = time.getMinutes();
  var seconds = time.getSeconds();
  // 小于10分钟前面补零
  if (hours < 10) hours = "0" + hours;
  if (minutes < 10) minutes = "0" + minutes;
  if (seconds < 10) seconds = "0" + seconds;

  if (data == 'year') return year;
  if (data == 'date') return year + "-" + month + "-" + dates;
  if (data == 'second') return year + "-" + month + "-" + dates + " " + hours + ':' + minutes + ':' + seconds;
  if (data == 'week') return year + "-" + month + "-" + dates + " " + hours + ':' + minutes + ':' + seconds + ' ' + arr[day];
}

//14.获取当前日期的一个月前日期
export function getMonthDates() {
  var date1 = new Date();
  var date2 = new Date(date1);
  date2.setDate(date1.getDate() - 30);
  //30天前(月份判断是否小于10,小于10的前面+0)
  var oldDay = `${date2.getFullYear()}-${date2.getMonth() + 1 < 10 ? `0${date2.getMonth() + 1}` : date2.getMonth() + 1}-${date2.getDate()}`;
  //当前日期
  var today = `${date1.getFullYear()}-${date1.getMonth() + 1 < 10 ? `0${date1.getMonth() + 1}` : date1.getMonth() + 1}-${date1.getDate()}`;
  let date = [oldDay, today]
  return date
}

//15.去重
export const unique = (arr) => {
  if (Array.hasOwnProperty('from')) {
    return Array.from(new Set(arr));
  } else {
    var n = {}, r = [];
    for (var i = 0; i < arr.length; i++) {
      if (!n[arr[i]]) {
        n[arr[i]] = true;
        r.push(arr[i]);
      }
    }
    return r;
  }
}

// 16.数组对象去重
export function deWeight(arr, val) {
  for (var i = 0; i < arr.length - 1; i++) {
    for (var j = i + 1; j < arr.length; j++) {
      if (arr[i][val] == arr[j][val]) {
        arr.splice(j, 1);
        //因为数组长度减小1,所以直接 j++ 会漏掉一个元素,所以要 j--
        j--;
      }
    }
  }
  return arr;
}

//17.求两个集合的并集
export const union = (a, b) => {
  var newArr = a.concat(b);
  return this.unique(newArr);
}

//18.求两个集合的交集
export const intersect = (a, b) => {
  var _this = this;
  a = this.unique(a);
  return this.map(a, function (o) {
    return _this.contains(b, o) ? o : null;
  });
}

// 19.删除其中一个元素
export const remove = (arr, ele) => {
  var index = arr.indexOf(ele);
  if (index > -1) {
    arr.splice(index, 1);
  }
  return arr;
}

//20.将类数组转换为数组
export const formArray = (ary) => {
  var arr = [];
  if (Array.isArray(ary)) {
    arr = ary;
  } else {
    arr = Array.prototype.slice.call(ary);
  }
  ;
  return arr;
}

//21.去除空格,type: 1-所有空格 2-前后空格 3-前空格 4-后空格
export const trim = (str, type) => {
  type = type || 1
  switch (type) {
    case 1:
      return str.replace(/\s+/g, "");
    case 2:
      return str.replace(/(^\s*)|(\s*$)/g, "");
    case 3:
      return str.replace(/(^\s*)/g, "");
    case 4:
      return str.replace(/(\s*$)/g, "");
    default:
      return str;
  }
}

// 22.是否为空对象
export function isObjectEmpty(val) {
  if (JSON.stringify(val) === '{}') {
    return true;
  }
  return false;
}

// 23.数组对象转树形结构
export function toTree(data) {
  // 空数组
  let result = [];
  // 判断不是数组  直接返回
  if (!Array.isArray(data)) {
    return result
  }
  // 遍历  删除  children 属性  做初始化操作
  data.forEach(item => {
    delete item.children;
  });
  //  空对象
  let map = {};
  data.forEach(item => {
    map[item.id] = item;
  });

  /**
   * map对象的 键: 是每个id  值:对应的item
   * 1: {id: 1, parentId: 0, name: "body"}
   * 2: {id: 2, parentId: 1, name: "title"}
   * 3: {id: 3, parentId: 2, name: "div"}
   */
  data.forEach(item => {
    // item.parentId 为0时 返回underfined
    let parent = map[item.parentId];
    if (parent) {
      (parent.children || (parent.children = [])).push(item);
    } else {
      // 这里push的item是parentId为0的数据
      result.push(item);
    }
  });
  return result;
}

//24. 转base64
export function getBase64(file) {
  return new Promise((resolve, reject) => {
    let reader = new FileReader();
    let fileResult = "";
    reader.readAsDataURL(file);
    reader.onload = () => {
      fileResult = reader.result;
    };
    reader.onerror = (error) => {
      reject(error);
    };
    reader.onloadend = () => {
      resolve(fileResult);
    };
  });
}

//25.通过身份证号获取出生年月日,性别,年龄
export function IdCard(IdCard, type) {
  if (type === 1) {
    //获取出生日期
    let birthday = IdCard.substring(6, 10) + "-" + IdCard.substring(10, 12) + "-" + IdCard.substring(12, 14)
    return birthday
  }
  if (type === 2) {
    //获取性别
    if (parseInt(IdCard.substr(16, 1)) % 2 === 1) {
      return "1"
    } else {
      return "2"
    }
  }
  if (type === 3) {
    //获取年龄
    var ageDate = new Date()
    var month = ageDate.getMonth() + 1
    var day = ageDate.getDate()
    var age = ageDate.getFullYear() - IdCard.substring(6, 10) - 1
    if (IdCard.substring(10, 12) < month || IdCard.substring(10, 12) === month && IdCard.substring(12, 14) <= day) {
      age++
    }
    if (age <= 0) {
      age = 1
    }
    return age
  }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值