如何在页面重载时提取querystring中同名参数值并存入数组
QueryString重复参数提取为数组实现方案
方案1:现代浏览器原生API实现(推荐)
核心使用ES6新增的URLSearchParams接口,内置支持重复参数的批量获取,无需手动解析:
window.addEventListener('load', () => { // 解析当前页面查询参数 const searchParams = new URLSearchParams(window.location.search); // getAll方法直接返回指定参数的所有值组成的数组 const cityList = searchParams.getAll('city'); // 后续业务逻辑 console.log(cityList); // 示例输出:["Los Angeles", "abc Plan", "xyz"] })
方案2:全兼容手动实现(适配IE等老浏览器)
如果需要兼容不支持URLSearchParams的低版本环境,可以手动拆分解析查询字符串:
window.addEventListener('load', () => { const cityList = []; const queryStr = window.location.search.slice(1); // 移除开头的? if (!queryStr) return; // 拆分所有参数键值对 const paramPairs = queryStr.split('&'); paramPairs.forEach(pair => { const [rawKey, rawValue] = pair.split('='); const key = decodeURIComponent(rawKey); const value = decodeURIComponent(rawValue || ''); if (key === 'city') { cityList.push(value); } }) // 后续业务逻辑 console.log(cityList); })
验证说明
针对你给出的示例链接,两种方案最终返回的city数组均为["Los Angeles", "abc Plan", "xyz"],可直接用于后续业务操作。
内容的提问来源于stack exchange,提问作者Ms1
相关产品推荐
相关产品推荐

