格式化地址栏字符串成对象
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>格式化地址栏字符串成对象</title> </head> <body> <script type="text/javascript"> var str = "http://www.aabbcc.com?name=jack&age=30&sex=0"; //创造一个类似的网址 function fun(str){ var str1 = str.split("?")[1]; //把字符串于?位置分割成字符串数组
//console.log(str1)为name=jack&age=30&sex=0
var str2 = str1.split("&"); //把字符串于&位置分割成字符串数组
//console.log(str2)为["name=jack", "age=30", "sex=0"] var obj = {} //创建对象 for(var i = 0;i<str2.length;i++){ var a = str2[i].split("=");
//console.log(a)为 ["age","30"]
["name","jack"]
["sex","0"]
obj[a[0]] = a[1] //
} return obj //返回obj的值
} console.log(fun(str)); //结果为{age:"30",name:"jack",sex:"0"}
</script> </body> </html>