我使用此函数来解析url参数
function parseURL(url) {
var a = document.createElement('a');
a.href = url;
return {
source: url,
protocol: a.protocol.replace(':',''),
host: a.hostname,
port: a.port,
query: a.search,
params: (function(){
var ret = {},
seg = a.search.replace(/^\?/,'').split('&'),
len = seg.length, i = 0, s;
for (;i<len;i++) {
if (!seg[i]) { continue; }
s = seg[i].split('=');
ret[s[0]] = s[1];
}
return ret;
})(),
file: (a.pathname.match(/\/([^\/?#]+)$/i) || [,''])[1],
hash: a.hash.replace('#',''),
path: a.pathname.replace(/^([^\/])/,'/$1'),
relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [,''])[1],
segments: a.pathname.replace(/^\//,'').split('/')
};
}
我可以通过以下方式调用此函数:
var currentURL = parseURL(window.location.href);
console.log(currentURL.params['price']);
但我想弄清楚params的长度......以验证是否已经有任何参数。
console.log(currentURL.params.length) // doesn't work -> returns undefined
现在你问我:为什么你想知道长度?因为我有另一个功能:
function filter(type, currentURL){
var result = "";
var url = document.location.href;
if(currentURL.params[type] != undefined){
var price = currentURL.params[type];
if(url.indexOf('&' + type + '=asc') > 0){
result = url.replace("&" + type + "=asc", "&" + type + "=desc");
}else if(url.indexOf("?" + type + "=asc") > 0){
result = url.replace("?" + type + "=asc", "?" + type + "=desc");
}else if(url.indexOf("&" + type + "=desc") > 0){
result = url.replace("&" + type + "=desc", "&" + type + "=asc");
}else if(url.indexOf("?" + type + "=desc") > 0){
result = url.replace("?" + type + "=desc", "?" + type + "=asc");
}
}else{
result = url + "&" + type + "=asc";
if(currentURL.length == 0){
// The problem is here
result = url + "?" + type + "=asc";
}
}
return result;
}
因为如果我没有参数,我应该放置:index.php?price=asc
而不是index.php&price=asc
。
使用@Pointy帮助编辑:解决。
result = url + "&" + type + "=asc";
if(window.location.search.length == 0){
result = url + "?" + type + "=asc";
}
答案 0 :(得分:1)
除非您明确制作一个数组和字符串,否则只有length
相反,您可以拨打Object.keys(x).length
。