跳到主要内容

将 url 参数解析为 JS 对象

还是比如:http://localhost/test/test.html?a=100&b=200#c=300

// 传统方式,分析 search
function queryToObj(){
const res = {}
// 去掉前面的 '?'
const search = location.search.substr(1)
search.split('&').forEach(str=>{
const arr = str.split('=')
res[arr[0]] = arr[1]
})
return res
}
console.log(queryToObj()) // {a: "100", b: "200"}

高级 API 方法

// 使用 URLSearchParams
function searchToObj(){
const res = {}
const pList = new URLSearchParams(location.search)
pList.forEach((val,key)=>{
res[key] = val
})
return res
}
console.log(searchToObj()) // {a: "100", b: "200"}