一、 js-時間處理函數
項目需要,會用到很多時間處理函數,總結至此。有未提及的相關工具類方法或者有更高效的方法,希望大家留言補充。
時間格式化
//很給力的函數,幾乎覆蓋所有日期格式輸出
//時間格式化
function formatDate(date,fmt){
if(/(y+)/.test(fmt)){
fmt = fmt.replace(RegExp.$1, (date.getFullYear()+'').substr(4-RegExp.$1.length));
}
let o = {
'M+': date.getMonth()+1,
'd+': date.getDate(),
'h+': date.getHours(),
'm+': date.getMinutes(),
's+': date.getSeconds()
}
for(let k in o){
let str = o[k]+'';
if(new RegExp(`(${k})`).test(fmt)){
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length===1)?str:padLeftZero(str));
}
}
return fmt;
};
function padLeftZero(str){
return ('00'+str).substr(str.length);
}
//測試代碼
console.log(formatDate(new Date(),'yyyyMMdd'))
console.log(formatDate(new Date(),'yyyy-MM-dd'))
console.log(formatDate(new Date(),'yyyy/MM/dd'))
console.log(formatDate(new Date(),'yyyyMd hh:mm:ss'))
計算幾個月前的當天日期
//計算幾個月前的當天日期,date爲日期對象,onthSpace爲月份間隔,返回格式 yyyyMMdd
function getLastMonthDate(date, monthSpace) {
let d = new Date(date.getTime());
let newD = new Date(d.setMonth(d.getMonth() - monthSpace));
return formatDate(newD, 'yyyyMMdd');
};
//測試代碼
console.log(getDays(new Date('2018/09/10'),new Date('2018/09/12')))
console.log(getLastMonthDate(new Date('2018/01/01'),1))
日期加減
//日期加減 date爲日期對象,num爲日期加減數目
function daysAddSub(date, num) {
let d = new Date(date.getTime());
let newD = new Date(d.setDate(d.getDate() + num));//設置天數 +1 天
return formatDate(newD, 'yyyyMMdd');
}
//測試代碼
console.log(daysAddSub(new Date('2018/08/01'), -1));
console.log(daysAddSub(new Date('2018/06/28'),3));
獲得兩個日期之間相差的天數
//獲得兩個日期之間相差的天數,date1,date2爲日期對象
function getDays(date1, date2) {
const dateTime = 1000 * 60 * 60 * 24; //每一天的毫秒數
const minusDays = Math.floor(((date2.getTime() - date1.getTime()) / dateTime));//計算出兩個日期的天數差
return Math.abs(minusDays);
}
得到date當月第一天或最後一天
//獲取date當月的第一天或者最後一天,last爲ture表示獲取最後一天
function getMonthSomeDay(date, last=false) {
let d = new Date();
if(!last){
d= new Date(date.getFullYear(), date.getMonth() , 1);
}else{
d = new Date(date.getFullYear(), date.getMonth() +1, 0);
}
return formatDate(d, 'yyyyMMdd');
}
//測試代碼
console.log(getMonthSomeDay(new Date('2018/01/01')));
console.log(getMonthSomeDay(new Date('2018/01/01'), false));
console.log(getMonthSomeDay(new Date('2018/01/31'), true));
二、 js–json相關處理函數
封裝 JSON.parse 防止發生錯誤頁面白屏
// 封裝 JSON.parse 防止發生錯誤頁面白屏
import { Modal } from 'antd';
function parseJson(str, name) {
let obj = null;
if (str && str != '') {
try {
obj = JSON.parse(str);
} catch (err) {
Modal.error({
title: '解析 json 字符串出錯',
content: `變量名爲 ${name}, 字符串爲: ${str}, 錯誤: ${JSON.stringify(err)}`
});
}
}
return obj;
}
export default parseJson;
判斷是否爲JSON字符串
//判斷是否爲JSON字符串
function isJsonString(str) {
try {
if (typeof JSON.parse(str) == "object") {
return true;
}
} catch (e) {
return false;
}
return false;
}
三、Math類
生成隨機字符串
//length爲隨機字符串的長度(範圍爲1~12)
function randomId() {
return (Math.random() * 1e18)
.toString(36)
.slice(0, length)
.toUpperCase();
}
//測試代碼
console.log(randomId(1));
console.log(randomId(3));
console.log(randomId(12));
console.log(randomId(13)); //若length超出12,也返回12位字符串。如需要長度超出12的隨機字符串,可以修改1e18的值,一般1~12位足夠用。
四、數組類
僞數組轉爲數組
function fakeToArray(obj) {
/*方法一:*/
// const arr = [].slice.call(obj);
/*方法二:*/
// const arr = [].concat.apply([], obj);
/*方法三*/
let arr = [];
arr.push.apply(arr, obj);
return arr;
}
//測試代碼
let fakeArrayObj = { 0: 'a', 1: 'b', length: 2 };//這是一個標準的僞數組對象
console.log(fakeToArray(fakeArrayObj));
數組去重
//1. 遍歷,數組下標去重法
//時間複雜度:O(n^2),indexOf本身也消耗了O(n)的複雜度,空間複雜度:O(n)
//IE8以下不支持indexOf
Array.prototype.removeRepeat1 = function() {
var res =[this[0]];
for(var i=1; i<this.length;i++){ //從第二項開始遍歷
if(this.indexOf(this[i])==i){
res.push(this[i]);
}
}
return res;
};
//2。hash去重法
//時間複雜度:O(n),空間複雜度:O(n)
Array.prototype.removeRepeat2 = function() {
var h= {}; //哈希表
var res = [];
for(var i=0; i<this.length;i++){
if(!h[this[i]]){ //如果hash表中沒有當前項
h[this[i]]=true; //存入hash表
res.push(this[i]);
}
}
return res;
};
哈希去重法,相比較於使用傳統數組遍歷,再使用indexOf判斷是否存在的方法(時間複雜度O(n2), 空間複雜度O(n)),更高效些。此外,還可以使用es6的Set方法,參見博客:js數組去重的五個方法
更多關於數組的問題,可參見js-基本數據類型-你不知道的趣味題
五、URL相關
讀取URL參數值
/**
* 得到通過get方式在URL中傳入的參數值
**/
function getUrlParam(url, name) {
//構造一個含有目標參數的正則表達式對象
const reg = new RegExp("(^|&)*" + name + "=([^&]*)(&|$)");
//匹配目標參數
let r = url.match(reg);
//返回參數值
if (r != null) return decodeURIComponent(r[2]);
return null;
};
//測試代碼
let url = '/625306/issue?projectId=625306&';
let url1 = 'history.get/1.0/?jsv=2.4.0&appKey=246&t=1530450922488&sign=8554910562a874dd127ff7b9e00dcdba&api=history.get&ecode=1&v=1.0&data=%7B%22requestStr%22%3A%22%7B%5C%22header%5C%22%3A%7B%7D%2C%5C%22model%5C%22%3A%7B%5C%22from%5C%22%3A%5C%222018-05-01%5C%22%2C%5C%22to%5C%22%3A%5C%222018-06-30%5C%22%7D%7D%22%7D';
console.log(getUrlParam(url,'akProjectId'));
console.log(getUrlParam(url,'akProjectId1'));
console.log(getUrlParam(url1,'appKey'));
console.log(getUrlParam(url1,'api'));
console.log(getUrlParam(url1,'data'));
解析url參數,返回參數對象
function parseURI(uri){
var obj = {};
var query = uri.split("?")[1];
var queryArr = query.split("&");
queryArr.forEach(function(item){
var key = item.split("=")[0];
var value = item.split("=")[1];
obj[key] = value;
});
return obj;
}
//正則表達式:
function getQueryObject(url) {
url = url == null ? window.location.href : url;
let search = url.substring(url.lastIndexOf("?") + 1);
let obj = {};
let reg = /([^?&=]+)=([^?&=]*)/g;
// [^?&=]+表示:除了?、&、=之外的一到多個字符
// [^?&=]*表示:除了?、&、=之外的0到多個字符(任意多個)
search.replace(reg, function (rs, $1, $2) {
let name = decodeURIComponent($1);
let val = decodeURIComponent($2);
obj[name] = val+'';
return rs;
});
return obj;
}
console.log(getQueryObject('https://www.baidu.com/baidu?tn=monline_3_dg&ie=utf-8&wd=12306%E7%81%AB%E8%BD%A6%E7%A5%A8%E7%BD%91%E4%B8%8A%E8%AE%A2%E7%A5%A8%E5%AE%98%E7%BD%91'));
// Object {tn: "monline_3_dg", ie: "utf-8", wd: "12306火車票網上訂票官網"}
改變url參數,替換指定傳入參數的值
//改變url參數,替換指定傳入參數的值,paramName爲參數,replaceWith爲新值
function replaceParamVal(url, paramName,replaceWith) {
let reg=new RegExp('('+ paramName+'=)([^&]*)','gi');
let nUrl = url.replace(reg, paramName+'='+replaceWith);
return nUrl;
}
//測試代碼
var url = "http://guyulei.html?a=1&b=2&c=3&d=4&d=9";
console.log(replaceParamVal("a",888));
console.log(replaceParamVal("b",999));
console.log(replaceParamVal("d","sdf")); //全局替換,忽略大小寫
console.log(replaceParamVal("a","er"));
六、字符串類
數字格式化–三個數字一個逗號
//方法一
var num_s = "1232134456.546 ";
parseFloat(num_s).toLocaleString();
//方法二
function format_number(n){
var b=parseInt(n).toString();
var len=b.length;
if(len<=3){return b;}
var r=len%3;
return r>0?b.slice(0,r)+","+b.slice(r,len).match(/\d{3}/g).join(","):b.slice(r,len).match(/\d{3}/g).join(",");
}
var a="53669988.000";
alert(format_number(a));
alert(format_number("wahh"));
alert(format_number(0));
alert(format_number(6698.0023));
七、性能類
throttling
throttling(fn, wait, maxTimelong) {
let timeout = null,
startTime = Date.parse(new Date());
return function() {
if (timeout !== null) clearTimeout(timeout);
var curTime = Date.parse(new Date());
if (curTime - startTime >= maxTimelong) {
fn();
startTime = curTime;
} else {
timeout = setTimeout(fn, wait);
}
};
}
//使用
window.addEventListener(
"scroll",
this.throttling(this.handleScroll, 1000, 300)
);
八、待補充
…