我需要在對象中獲取URL搜索參數,例如: http://example.com/?a=x&b=y&d#pqr
應該產生{a:x, b:y, d:1}
JavaScript - 改進URL參數獲取算法
下面是我用來得到這個的方法,我該如何改進?任何suggessions ...
var urlParamKeyVals = new Array();
var pieces = new Array();
var UrlParams = {};
if(window.location.search.length){
var urlSearchString = window.location.search;
if(urlSearchString.charAt(0) == '?'){
urlSearchString = urlSearchString.substr(1);
urlParamKeyVals = urlSearchString.split("&");
}
}
for (var i = 0; i<urlParamKeyVals .length; i++) {
pieces = urlParamKeyVals [i].split("=");
if(pieces.length==1){
UrlParams[pieces[0]]=1;
} else {
UrlParams[pieces[0]]=pieces[1];
}
}
UrlParams;
不需要'unescape'? – sje397 2010-07-19 15:16:07
@ sje397:是的,但我會使用'decodeURIComponent'而不是'unescape'。 – CMS 2010-07-19 15:20:47
'getQueryStringValues(「http://example.com/?a&b=y&d#pqr」)'outputs'{b:'y'}',它應該是'{a:1,b:'y':d: 1}' – 2010-07-19 15:24:52