JavaScript对象、数组、日期操作方法封装
1.获取对象属性个数 objLength(obj) {
var count = 0;
for(var i in obj) {
if(obj.hasOwnProperty(i)) {
count++;
}
}
return count;
},
2.数组排序 sortArr(arr,s){
// s:true 升序 false 降序
var s = '' || s;
arr.sort(function (a, b) {
if (s) {//从小到大排序
return a - b;
}else{//从大到小排序
return b - a;
}
});
return arr;//返回已经排序的数组
},
3.根据数组对象中的某个属性值进行排序的方法 sortBy(arr,attr,rev){
/*** arr 需要排序的数组
* attr 排序的属性 如number属性
* rev true表示升序排列,false降序排序
* */
//第二个参数没有传递 默认升序排列
if(rev == undefined){
rev = 1;
}else{
rev = (rev) ? 1 : -1;
}
return arr.sort(function(a,b){
a = a[attr];
b = b[attr];
if(a < b){
return rev * -1;
}
if(a > b){
return rev * 1;
}
return 0;
})
},
4.数组去重 unique(arr) {
return Array.from(new Set(arr))
},
5.根据数组对象的某个属性进行去重 uniqueObj(arr1,from) {
// arr1:要去重的数组 from:属性
const res = new Map();
return arr1.filter((a) => !res.has(a[from]) && res.set(a[from], 1))
},
6.对象数组去重并且保留最后的对象 arrayUnique2(arr, name) {
var hash = {};
return arr.reduce(function (acc, cru,index) {
if (!hash[cru[name]]) {
hash[cru[name]] = {index:index}
acc.push(cru)
}else{
acc.splice(hash[cru[name]]['index'],1,cru)
}
return acc;
}, []);
},
7.删除数组中小于某个值的元素 handleArr(arr,smail){
// arr:数组 small:需要比这个值小
var newArr = arr.filter(item => item > smail);
return newArr;
},
8.将一个数组等分成若干个数组,每个数组里有n条数据 bisectionArr(arr,n){
/**arr:数据 n每个数组里保留几条数据
* 用法
* app.bisectionArr(this.data.Arr,5);
**/
var n=Number(n);
var newarr = [];
var len = arr.length / n;
len = Math.ceil(len);
for (var j = 1; j <= len; j++) {
newarr[j - 1] = [];
for (var i = (n * j - n); i < n * j; i++) {
if (arr[i] != undefined) {
newarr[j - 1].push(arr[i]);
}
}
}
return newarr;
},
9.根据身份证号获取出生年月日 getBirthdayFromIdCard(idCard) {
var birthday = "";
if (idCard != null && idCard != "" && checkIdcard(idCard)) {
if (idCard.length == 15) {
birthday = "19" + idCard.substr(6, 6);
} else if (idCard.length == 18) {
birthday = idCard.substr(6, 8);
}
birthday = birthday.replace(/(.{4})(.{2})/, "$1-$2-");
}
return birthday;
},
10.只能输入金额 onlyMoney(val){
var regStrs = [
['^0(\\d+)$', '$1'], //禁止录入整数部分两位以上,但首位为0
['[^\\d\\.]+$', ''], //禁止录入任何非数字和点
['\\.(\\d?)\\.+', '.$1'], //禁止录入两个以上的点
['^(\\d+\\.\\d{2}).+', '$1'] //禁止录入小数点后两位以上
];
for(var i=0; i<regStrs.length; i++){
var reg = new RegExp(regStrs[i][0]);
val = val.replace(reg, regStrs[i][1]);
}
return val;
},
11.根据身份证号返回所在省 getProvinceFromIdCard(idCard) {
var aCity={11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",21:"辽宁",22:"吉林",23:"黑龙江 ",31:"上海",32:"江苏",33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南",42:"湖北 ",43:"湖南",44:"广东",45:"广西",46:"海南",50:"重庆",51:"四川",52:"贵州",53:"云南",54:"西藏 ",61:"陕西",62:"甘肃",63:"青海",64:"宁夏",65:"新疆",71:"台湾",81:"香港",82:"澳门",91:"国外"};
return aCity[idCard.substr(0,2)];
},
12.获取当前日期 getNowDate(){
var date=new Date();
var year=date.getFullYear();
var month=date.getMonth()+1;
var day=date.getDate();
var hh=date.getHours();
var mm=date.getMinutes();
var ss=date.getSeconds();
var arr=['日','一','二','三','四','五','六'];
var week=arr[date.getDay()];
function add0(val){
return (val<10? '0'+val : val);
}
month=add0(month);day=add0(day);hh=add0(hh);mm=add0(mm);ss=add0(ss);
return {
data:year+'-'+month+'-'+day+' '+hh+':'+mm+':'+ss,
year:year,
month:month,
day:day,
hh:hh,
mm:mm,
ss:ss,
week:week,
};
},
13.日期转时间戳 dateToChuo(riqi){
//riqi格式 2020-01-01 00:00:00
riqi=riqi.replace(/-/g,"/");
var date = new Date(riqi);//兼容ios
var time = parseInt(date.getTime()/1000);//除以1000为10位时间戳 不除为13位
return time;
},
14.时间戳转日期 chuoToDate(timestamp){
if(!timestamp){
return false;
}
timestamp=timestamp.toString().length<13? (timestamp * 1000):timestamp;
var date = new Date(timestamp);//时间戳为10位需*1000,时间戳为13位的话不需乘1000
var Y = date.getFullYear();
var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
var D = (date.getDate()<10? '0'+date.getDate() : date.getDate());
var h = (date.getHours()<10? '0'+date.getHours() : date.getHours());
var m = (date.getMinutes()<10? '0'+date.getMinutes() : date.getMinutes());
var s = (date.getSeconds()<10? '0'+date.getSeconds() : date.getSeconds());
// + h + m + s
return {
data:Y+'-'+M+'-'+D+' '+h+':'+m+':'+s,
year:Y,
month:M,
day:D,
hh:h,
mm:m,
ss:s
}
},
15.获取当前时间的后20分钟、后一小时(add是正数)、前一天(add是负数)等等相对时间 setDefaultTime(add,danwei){
// 调用方法:app.setDefaultTime(20,'天');20天以后的时间
var danwei=danwei || '秒';//默认单位是秒
if(danwei=='秒'){
add=add*1000;// add 单位是秒
}else if(danwei=='分'){
add=add*1000*60;// add 单位是分
}else if(danwei=='时'){
add=add*1000*60*60;// add 单位是时
}else if(danwei=='天'){
add=add*1000*60*60*24;// add 单位是天
}
let t = new Date().getTime() + add;
let d = new Date(t);
let theMonth = d.getMonth() + 1;
let theDate = d.getDate();
let theHours = d.getHours();
let theMinutes = d.getMinutes();
let getSeconds=d.getSeconds();
function add0(val){
return (val<10? '0'+val : val);
}
theMonth=add0(theMonth);
theDate=add0(theDate);
theHours=add0(theHours);
theMinutes=add0(theMinutes);
getSeconds=add0(getSeconds);
let date = d.getFullYear() + '-' + theMonth + '-' + theDate;
let time = theHours + ':' + theMinutes + ':' + getSeconds;
let Spare = date + ' ' + time;
return {
datas:d.getFullYear()+'-'+theMonth+'-'+theDate,
data:Spare,
year:d.getFullYear(),
month:theMonth,
day:theDate,
hh:theHours,
mm:theMinutes,
ss:getSeconds
}
},
16.已知开始日期和结束日期 计算出中间的所有日期 getAllDate(start, end){
// start:2020-07-14 end:2020-07-20
let dateArr = []
let startArr = start.split('-')
let endArr = end.split('-')
let db = new Date()
db.setUTCFullYear(startArr[0], startArr[1] - 1, startArr[2])
let de = new Date()
de.setUTCFullYear(endArr[0], endArr[1] - 1, endArr[2])
let unixDb = db.getTime()
let unixDe = de.getTime()
let stamp
const oneDay = 24 * 60 * 60 * 1000;
for (stamp = unixDb; stamp <= unixDe;) {
// parseInt(stamp) 13位的时间戳
dateArr.push(this.format(new Date(parseInt(stamp))))
stamp = stamp + oneDay
}
return dateArr
},
format(time){
// time=new Date(13位的时间戳)
let ymd = ''
let mouth = (time.getMonth() + 1) >= 10 ? (time.getMonth() + 1) : ('0' + (time.getMonth() + 1))
let day = time.getDate() >= 10 ? time.getDate() : ('0' + time.getDate())
ymd += time.getFullYear() + '-' // 获取年份。
ymd += mouth + '-' // 获取月份。
ymd += day // 获取日。
return ymd // 返回日期。2020-07-14
},
17.获取上个月的年月 getLastMonth(riqi){
riqi=riqi.replace(/-/g,"/");
var date = new Date(riqi);
var year = date.getFullYear();
var month = date.getMonth();
if(month == 0){
year = year -1;
month = 12;
}
return {
year:year,
month:month<10? '0'+month : month
};
},
18.获取指定日期的星期 getWeek(riqi){
riqi=riqi.replace(/-/g,"/");
var date = new Date(riqi);//兼容ios
var arr=['日','一','二','三','四','五','六'];
var week=arr[date.getDay()];
return week;
},
19.当前日期是今年的第几周 getYearWeek(year,month,date){
/* app.getYearWeek(2019,4,19)
dateNow是当前日期
dateFirst是当年第一天
dataNumber是当前日期是今年第多少天
用dataNumber + 当前年的第一天的周差距的和在除以7就是本年第几周
*/
let dateNow = new Date(year, parseInt(month) - 1, date);
let dateFirst = new Date(year, 0, 1);
let dataNumber = Math.round((dateNow.valueOf() - dateFirst.valueOf()) / 86400000);
return Math.ceil((dataNumber + ((dateFirst.getDay() + 1) - 1)) / 7);
},
20.当前日期是当月的第几周 getMonthWeek(year,month,date){
/* app.getMonthWeek(2019,4,19)
month = 6 - w = 当前周的还有几天过完(不算今天)
year + month 的和在除以7 就是当天是当前月份的第几周
*/
let dateNow = new Date(year, parseInt(month) - 1, date);
let w = dateNow.getDay();//星期数
let d = dateNow.getDate();
return Math.ceil((d + 6 - w) / 7);
},
21.判断某年某月有多少天 getCountDays(ym) {
var curDate = new Date(ym.replace(/-/g,"/"));
/* 获取当前月份 */
var curMonth = curDate.getMonth();
/* 生成实际的月份: 由于curMonth会比实际月份小1, 故需加1 */
curDate.setMonth(curMonth + 1);
/* 将日期设置为0 */
curDate.setDate(0);
/* 返回当月的天数 */
return curDate.getDate();
},
22.获取指定日期的第几个月 getHowMonth(date,num) {
// date 格式为yyyy-mm-dd的日期,如:2014-01-25
// num 第几个月 下一个月 1 下两个月 2 上一个月-1 上两个月-2 以此类推
date=date.replace(/-/g,"/");
var dt=new Date(date);
return this.chuoToDate(dt.setMonth(dt.getMonth() + Number(num)));
},
23.计算两个日期之间相差的年月日 monthDayDiff(startDate,endDate) {
let flag = [1, 3, 5, 7, 8, 10, 12, 4, 6, 9, 11, 2];
let start = new Date(startDate);
let end = new Date(endDate);
let year = end.getFullYear() - start.getFullYear();
let month = end.getMonth() - start.getMonth();
let day = end.getDate() - start.getDate();
if (month < 0) {
year--;
month = end.getMonth() + (12 - start.getMonth());
}
if (day < 0) {
month--;
let index = flag.findIndex((temp) => {
return temp === start.getMonth() + 1
});
let monthLength;
if (index <= 6) {
monthLength = 31;
} else if (index > 6 && index <= 10) {
monthLength = 30;
} else {
monthLength = 28;
}
day = end.getDate() + (monthLength - start.getDate());
}
return {
year,month,day
};
},
24.计算两个时间之间的差 diffTime(startDate,endDate) {
//用法 diffTime('2017-03-02 09:10:10','2017-03-17 04:10:12')
startDate=startDate.replace(/-/g,'/');//ios兼容
endDate=endDate.replace(/-/g,'/');//ios兼容
startDate= new Date(startDate);
endDate = new Date(endDate);
var diff=endDate.getTime() - startDate.getTime();//时间差的毫秒数
//计算出相差天数
var days=Math.floor(diff/(24*3600*1000));
//计算出小时数
var leave1=diff%(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);
var returnStr = seconds + "秒";
if(minutes>0){ returnStr = minutes + "分" + returnStr;}
if(hours>0){returnStr = hours + "小时" + returnStr;}
if(days>0){returnStr = days + "天" + returnStr;}
return {
data:returnStr,
day:days,hh:hours,mm:minutes,ss:seconds
};
},
25.倒计时 countDown(jssj,success,times){
/*用法:app.countDown("2020-08-24 07:23:00",function(res){
console.log(res)
},1000)
jssj:设置结束时间 2020-08-10 12:12:12
times:设置倒计时的时间间隔
*/
fun();
var timer=setInterval(function(){
fun();
},times);
function fun(){
var lefttime = parseInt((new Date(jssj.replace(/-/g,"/")).getTime() - new Date().getTime()));
if(lefttime <= 0) {
success({day:"00",hour:"00",min:"00",sec:"00"});
clearInterval(timer);
return;
}
var d = parseInt(lefttime /1000 /3600 /24); //天数
var h = parseInt(lefttime / 1000 / 3600 % 24); //小时
var m = parseInt(lefttime / 1000 / 60 % 60); //分钟
var s = parseInt(lefttime / 1000 % 60); //当前的秒
d < 10 ? d = "0" + d : d;
h < 10 ? h = "0" + h : h;
m < 10 ? m = "0" + m : m;
s < 10 ? s = "0" + s : s;
success({ day: d, hour: h, min: m, sec:s })
}
},
26.多长时间之前 timeago(stringTime){
var minute = 1000 * 60;
var hour = minute * 60;
var day = hour * 24;
var week = day * 7;
var month = day * 30;
var time1 = new Date().getTime();//当前的时间戳
var time2 = Date.parse(new Date(stringTime));//指定时间的时间戳
var time = time1 - time2;
var result = "刚刚";
if (time < 0) {
console.log("设置的时间不能早于当前时间!");
} else if (time / month >= 1) {
// result = "" + parseInt(time / month) + "月前";
result=stringTime.slice(0,10);//大于等于1个月的时候显示具体日期
} else if (time / week >= 1) {
result=stringTime.slice(0,10);//大于等于1周的时候显示具体日期
// result = "" + parseInt(time / week) + "周前";
} else if (time / day >= 1) {
result = "" + parseInt(time / day) + "天前";
} else if (time / hour >= 1) {
result = "" + parseInt(time / hour) + "小时前";
} else if (time / minute >= 1) {
result = "" + parseInt(time / minute) + "分钟前";
} else {
result = "刚刚";
}
return result;
},
27.获取n到m之间的所有数 getNDMnumber(n,m){
// n,m是整数 且n<m;
var n=Number(n);
var m=Number(m);
var arr=[];
var i=n;
while(i<=m){
arr.push(i);
i++;
}
return arr;
},