总结一下常用的小工具底层方法
规范化时间显示
function formatTime(date){ var year = date.getFullYear() var month = date.getMonth() + 1 var day = date.getDate() var hour = date.getHours() var minute = date.getMinutes() var second = date.getSeconds() function formatNumber(n){ n = n.toString() return n[1] ? n : '0' + n } return [year, month, day].map(formatNumber).join('/') +' '+ [hour, minute, second].map(formatNumber).join(':') }
删除数组中指定项
function removeArrElement(arr, value){ for (var i=0;i<arr.length;i++){ if(arr[i] == value) { arr.splice(i,1); break; } } retrun arr; }
将a中与b索引相同的项的值都替换为b的值。
function extend(a,b){ for (var key in b){ if (b[key]){ a[key] = b[key] } } return a }
获取数组中的特定对象(如果key,value相同,就取得第一个的值)
function getElementByAttr(arr,key,value) { for(var i=0;i<arr.length;i++){ if(arr[i][key] == value){ return arr[i] } } return null }
将一个对象变为url传参的字符串形式
function objToParams(obj){ var arr = [] for(var key in obj){ if(obj[key]){ arr.push(key + "=" + obj[key]) } } return arr.join("&") }
向对象a中扩增对象b的属性值
function copyProp(a,b){
for(var key in b){
if(b[key]){
if(a[key]){
// 什么都别做
} else {
a[key] = b[key]
}
}
}
return a
}
判断是否为手机号
function isMobile(mobile) { var reg = /^[0123456789]{11}$/; if (!reg.test(mobile)){ return false } else { return true } }
根据生日判断周岁
function getAgeByBirthday(birthday){ var returnAge; var strBirthdayArr = birthday.split("-"); var birthYear = strBirthdayArr[0]; var birthMonth = strBirthdayArr[1]; var birthDay = strBirthdayArr[2]; var d = new Date(); var nowYear = d.getFullYear(); var nowMonth = d.getMonth() + 1; var nowDay = d.getDate(); if(nowYear == birthYear){ returnAge = 0; //同年 则为0岁 } else { var ageDiff = nowYear - birthYear; if(ageDiff > 0){ if (nowMonth == birthMonth) { var dayDiff = nowDay - birthDay;//日之差 if (dayDiff < 0) { returnAge = ageDiff - 1; } else { returnAge = ageDiff; } } else { var monthDiff = nowMonth - birthMonth;//月之差 if (monthDiff < 0) { returnAge = ageDiff - 1; } else { returnAge = ageDiff; } } } else { returnAge = -1;//返回-1 表示出生日期输入错误 晚于今天 } } return returnAge;//返回周岁年龄 }