测试地址为
1 https://www.sogou.com/tx?query=javascript&ie=utf8&_ast=1542338688&_asf=null&w=01029901&hdq=sogou-clse-f507783927f2ec27&duppid=1&cid=&cid=&s_from=result_up&sut=3994&sst0=1542345989626&lkt=0%2C0%2C0&sugsuv=00B66944761A10BC5B28AFF86BBCB412&sugtime=1542345989626
location对象
字符串转对象格式
1 getSearch(location.search.substring(1))
2 function getSearch(str){
3 str = str || undefined;
4 let obj = {};
5 if(str){//没有查询字符串返回空数组
6 let arr = str.split('&');
7 arr.forEach((el)=>{
8 let item = el.split('=')
9 obj[item[0]] = item[1];
10 })
11 console.log(obj)
12 }
13 return obj;
14 }
1、location对象的search属性拿到url中的查询字符串。传到我们提前封装好的getSearch数组中(或者这一步可以也封装到函数中,但那样函数就只能获取location的查询字符串了,不方便以后的扩展。所以将获取字符串这一步提了出来)。
substring(1)是为了删掉拿到的字符串中,第一位的'?'字符。
2、getSearch函数思路
先利用“&”关键字将字符串分割成包含所有键值对字符串的数组。
然后遍历数组,利用“=”关键字将数组的每一项再进行分割成新的多个数组。
每个数组的第0项作为对象的键,第1项作为数组的值。即可。
见上图和getSearch()函数