使用场景:查询字符串的拼凑成员过多
const paramObj = {
attrA: "test",
attrB: 10,
attrC: ["a","b","c"]
};
let queryStr = "";
获取查询字符串(JS版)
Object.keys(paramObj).forEach(attr => {
let value = paramObj[attr];
queryStr = queryStr + (value ? ((queryStr ? "&" : "") + attr + "=" + value) : "");
});
Object.keys(paramObj).forEach(attr => {
let value = paramObj[attr];
const isArray = Array.isArray(value);
if (!value || (isArray && !value.length)) return ;
queryStr = queryStr + (queryStr ? "&" : "") + attr + "=" + (isArray ? value.join("&" + attr + "="): value);
});
获取查询字符串(TS版)
type attrsModel = "attrA" | "attrB" | "attrC"
Object.keys(paramObj).forEach(attr => {
let value = paramObj[attr as attrsModel];
queryStr = queryStr + (value ? ((queryStr ? "&" : "") + attr + "=" + value) : "");
});
Object.keys(paramObj).forEach(attr => {
let value = paramObj[attr as attrsModel];
const isArray = Array.isArray(value);
if (!value || (isArray && !(value as any[]).length)) return ;
queryStr = queryStr + (queryStr ? "&" : "") + attr + "=" + (isArray ? (value as any[]).join("&" + attr + "="): value);
});