js url参数和对象互转

function param(a) {
var s = [],
rbracket = /\[\]$/,
isArray = function(obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
},
add = function(k, v) {
v = typeof v === 'function' ? v() : v === null ? '' : v === undefined ? '' : v;
s[s.length] = encodeURIComponent(k) + '=' + encodeURIComponent(v);
},
buildParams = function(prefix, obj) {
var i, len, key; if (prefix) {
if (isArray(obj)) {
for (i = 0, len = obj.length; i < len; i++) {
if (rbracket.test(prefix)) {
add(prefix, obj[i]);
} else {
buildParams(prefix + '[' + (typeof obj[i] === 'object' ? i : '') + ']', obj[i]);
}
}
} else if (obj && String(obj) === '[object Object]') {
for (key in obj) {
buildParams(prefix + '[' + key + ']', obj[key]);
}
} else {
add(prefix, obj);
}
} else if (isArray(obj)) {
for (i = 0, len = obj.length; i < len; i++) {
add(obj[i].name, obj[i].value);
}
} else {
for (key in obj) {
buildParams(key, obj[key]);
}
}
return s;
}; return buildParams('', a).join('&').replace(/%20/g, '+');
} function parseQueryString(url) {
var obj = {};
var keyvalue = [];
var key = "",
value = "";
var paraString = url.substring(url.indexOf("?") + 1, url.length).split("&");
for (var i in paraString) {
keyvalue = paraString[i].split("=");
key = keyvalue[0];
value = keyvalue[1];
obj[key] = value;
}
return obj;
}
上一篇:WorldWind源码剖析系列:插件列表视图类PluginListView和插件列表视图项类PluginListItem


下一篇:图解最小生成树 - 普里姆(Prim)算法