// 在数组上扩展一个删除指定项的方法 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 }
处理数组和时间的一些方法
最新推荐文章于 2024-06-13 02:48:16 发布