虽然location.search返回问号其中的每个字符串参数
可以创建一个函数,用以解析查询字符串,然后返回所有参数的一个对象
这个函数第一步先去掉查询字符串开头的问号。
前提是location.search中必须一或多个字符串。
所有参数被保存到args对象中,该对象以字面量形式创建。
根据和号(&)来分割查询字符串,并返回name=value格式的字符串数组。
下面的for循环会迭代这个数组,然后再根据等于分割每一项,从而返回第一项为参数名,第二项为参数值的数组,
再用decodeURLCompenent()解码name和value(因为查询字符串应该是被编码过的)。
最后,将name作为args对象的属性,将value作为相应属性的值。
let getQueryStringArags = function(){
//取得开头没有问号的字符串
let qs = (window.location.length > 0 ? window.location.search.substring(1) : ''),
//保存数据的对象
args = {};
//把每个参数添加到args
for(let item of qs.split('&').map(kv => kv.split('='))){
let name = decodeURIComponent(item[0]);
value = decodeURIComponent(itemm[1]);
if(name.length){
args[name] = value;
}
}
return args;
}