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;
}
 
 

猜你喜欢

转载自www.cnblogs.com/aisiqi-love/p/10154776.html