朋友問的一個面試題:有個url,要求獲取url 的參數,返回值為json格式。
簡單的寫了下,發筆記備份。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>simple a example for url to json</title> <script> var url = 'https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=0&rsv_idx=1&tn=baidu&wd=慕課&rsv_pq=e379bd8200001a8c&rsv_t=ea8cxrgm03IFb44zHA261P6KziPRXAekcjwsRJtUSKLUmKweFsZFXE%2BUSrU&rqlang=cn&rsv_enter=0&rs'; function url2json(url){ var index = -1, str = '', arr = [], length = 0, res = {}; if(url.indexOf('?')!=-1){ index = url.indexOf('?'); str = url.substring(index+1); arr = str.split('&'); length = arr.length; for(var i=0; i<length-1; i++){ res[arr[i].split('=')[0]] = arr[i].split('=')[1]; } }else{ res = {}; } return res; }; var result = url2json(url); //獲取json的鍵值對條數(模擬長度) var length = 0; for(var i in result){ length++; } //在頁面輸出 var tL = 0; document.write('{<br>'); for(var name in result){ tL++; if(tL == length){ document.write('  '+name+':'+result[name]+'<br>'); }else{ document.write('  '+name+':'+result[name]+',<br>'); } } document.write('}'); </script> </head> <body>