请编写一个JavaScript函数 parseQueryString,它的用途是把URL参数解析为一个对象
如:var url = ”http://www.taobao.com/index.php?key0=0&key1=1& key2=2”
var obj = new parseQueryString(url);
alert(obj.key0) // 输出0
1 <!DOCTYPE HTML> 2 <html lang="en"> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 5 <title>Web前端面试题 Js把URL中的参数解析为一个对象</title> 6 7 <body> 8 <script type="text/javascript"> 9 var url = "http://www.taobao.com/index.php?key0=0&key1=1&key2=2"; 10 11 12 function parseQueryString(url){ 13 var str = url.split("?")[1], //通过?得到一个数组,取?后面的参数 14 items = str.split("&"); //分割成数组 15 var arr,name,value; 16 17 for(var i=0; i<items.length; i++){ 18 arr = items[i].split("="); //["key0", "0"] 19 name = arr[0]; 20 value = arr[1]; 21 this[name] = value; 22 } 23 } 24 25 var obj = new parseQueryString(url); 26 alert(obj.key2) 27 </script> 28 29 </body> 30 </html>