思路
就是使用split+reduce组合,关于reduce方法,如果不熟,可以阅读我写的笔记。
《一文带你彻底搞懂js的Array.prototype.reduce()方法!》
实现
function getQueryArray(url) {
let query = url.split("?").pop().split("&");
let result = query.reduce(
(total, cur) => {
let tmpObj = {}
let t = cur.split("=")
tmpObj.name = t.shift()
tmpObj.value = t.shift()
total.push(tmpObj);
return total
},
[]
)
return (result)
}
let url = "http://www.runoob.com/index.php?id=1&image=awesome.jpg"
// let url = window.location.href // 当前页url
console.log(getQueryArray(url))
输出
[ { name: 'id', value: '1' }, { name: 'image', value: 'awesome.jpg' } ]