js 实现解析和构造Url参数
// 解析获取的 url 中的参数为对象 function parseQueryString(url) { if (!url) { return {}; } const qsArr = decodeURIComponent(url).split("?")[1].split("&"); return qsArr.reduce((a, b) => { const [key, val] = b.split("="); a[key] = val; return a; }, {}); } console.log(parseQueryString("http://www.xxx.com/d?a=&b=1&c")); // 解析对象为参数格式 function queryString(params = {}) { const data = Object.entries(params); const qs = data .map(([k, v]) => { let noVal = false; let isObject = false; if (!v) { noVal = true; } if (v instanceof Object) { isObject = true; } isObject = true; return `${encodeURIComponent(k)}=${ noVal ? "" : isObject ? JSON.stringify(v) : v }`; }) .join("&"); return qs; } console.log( queryString({ f: [1, 2, 3], e: { a: 1 }, a: 1, b: undefined, c: null, d: "", orgId: "1", to: "1661615999000", name: "a", }) );