1. 程式人生 > >tool公用工具方法

tool公用工具方法

/** * 獲取URL指定key的引數值 * @param {string} key * @returns {string} */ export function getQueryString(key: string): string { let reg = new RegExp('(^|&)' + key + '=([^&]*)(&|$)'); let r = window.location.search.substr(1).match(reg); if (r != null) { return decodeURIComponent(r[2]); } return ''; }   /** * 設定URL指定key的引數值 * @param {string} key * @param {string} value */ export function setQueryString(key: string, value: string): void { let reg = new RegExp('(^|&)' + key + '=([^&]*)(&|$)'); let r = window.location.search.substr(1).match(reg); let h = window.location.href; let targetStr = key + '=' + value; let resultStr; if (r) { if (r[2] === value) { return; } resultStr = h.replace(r[0], targetStr); } else { resultStr = h + (window.location.search ? '&' : '?') + targetStr; } window.location.href = resultStr; }   /** * 把指定日期弄成 'YYYYMMDD' 格式 * @param {Date} date JS日期物件 * @returns {string} 'YYYYMMDD' 格式的日期 */ export function getYYYYMMDD(date: Date): string { let year = date.getFullYear() + ''; let month = date.getMonth() + 1; let monthStr = month < 10 ? '0' + month : '' + month; let dateN = date.getDate(); let dateStr = dateN < 10 ? '0' + dateN : '' + dateN; return year + monthStr + dateStr; }   /** * 把兩個 Object 深度合併。把 source 合併到 target * @param {object|array} target 目標 object(或 array) * @param {object|array} source 要合併的 object(或 array) * @returns {object|array} target 把 target 返回 */ export function deepAssign(target, source) { let keys = Object.keys(source); for (let key of keys) { if ( target.hasOwnProperty(key) && typeof target[key] === 'object' && typeof source[key] === 'object' ) { deepAssign(target[key], source[key]); } else { target[key] = source[key]; } } return target; }   /** * 轉換物件為URL引數形式的方法 * @param {obj} * @returns {string} */ export function tranformParams(obj) { var query = '', name, value, fullSubName, subName, subValue, innerObj, i;
for (name in obj) { value = obj[name];
if (value instanceof Array) { for (i = 0; i < value.length; ++i) { subValue = value[i]; fullSubName = name + '[' + i + ']'; innerObj = {}; innerObj[fullSubName] = subValue; query += tranformParams(innerObj) + '&'; } } else if (value instanceof Object) { for (subName in value) { subValue = value[subName]; fullSubName = name + '[' + subName + ']'; innerObj = {}; innerObj[fullSubName] = subValue; query += tranformParams(innerObj) + '&'; } } else if (value !== undefined && value !== null) query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&'; }
return query.length ? query.substr(0, query.length - 1) : query; }