处理数组和时间的一些方法

// 在数组上扩展一个删除指定项的方法
Array.prototype.remove = function (item) {
  let index = this.findIndex((v) => v === item)
  if (index > -1) {
    this.splice(index, 1)
  }
}

// 清空数组
Array.prototype.empty = function () {
  this.splice(0, this.length)
}

// 在数组上扩展一个去重的方法
Array.prototype.unique = function (arg) {
  const res = new Map()
  return this.filter((m) => {
    if (arg) {
      return !res.has(m[arg]) && res.set(m[arg], 1)
    } else {
      return !res.has(m) && res.set(m, 1)
    }
  })
}

// 去除数组中的空字符串选项
Array.prototype.trim = function () {
  return this.filter((m) => m !== '')
}

// 按照数组中的指定key将数组进行分组
Array.prototype.groupByKey = function (key) {
  let res = {}
  this.forEach((m) => {
    let group = res[m[key]]
    if (!group) {
      group = []
      res[m[key]] = group
    }
    group.push(m)
  })
  return res
}

// 将数组对象中的某一个属性值单独抽取出来成为一个新的数组  [{id:'1',name:'苹果'},{id:'2',name:'香蕉'}].extractByKey("id") ==> ['1','2']
Array.prototype.extractByKey = function (key) {
  let set = new Set()
  this.forEach((m) => {
    if (key && m[key]) {
      set.add(m[key])
    }
  })
  return Array.from(set)
}

/**
 * 日期格式化。
 * 日期格式:
 * yyyy,yy 年份
 * MM 大写表示月份
 * dd 表示日期
 * hh 表示小时
 * mm 表示分钟
 * ss 表示秒
 * q  表示季度
 * 实例如下:
 * var now = new Date();
 * var nowStr = now.format("yyyy-MM-dd hh:mm:ss");
 */
Date.prototype.format = function (format) {
  var o = {
    'M+': this.getMonth() + 1, //month
    'd+': this.getDate(), //day
    'h+': this.getHours(), //hour
    'H+': this.getHours(), //hour
    'm+': this.getMinutes(), //minute
    's+': this.getSeconds(), //second
    'q+': Math.floor((this.getMonth() + 3) / 3), //quarter
    S: this.getMilliseconds(), //millisecond
  }

  if (/(y+)/.test(format)) {
    format = format.replace(
      RegExp.$1,
      (this.getFullYear() + '').substr(4 - RegExp.$1.length)
    )
  }

  for (var k in o) {
    if (new RegExp('(' + k + ')').test(format)) {
      format = format.replace(
        RegExp.$1,
        RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length)
      )
    }
  }
  return format
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值