我知道有各种库或方法可以从queryString获取数据。然而,我正在尝试学习一点javascript,所以我决定写我自己的,如下所示:
function parseQueryString() {
var qs = window.location.href.split('?')[1];
var item = qs.split('&');
var data = {};
for (var i=0; i < item.length; i++) {
key = item[i].split('=')[0];
value = item[i].split('=')[1];
data[key] = value;
}
return data;
}上面的看起来像是遗漏了什么,或者有什么缺点吗?如果是这样,我如何改进它?
发布于 2018-10-24 08:55:16
一些建议-考虑使用window.location.search直接访问查询字符串。
此外,您可能想要考虑查询字符串中存在“数组”的情况(即多个值共享相同的键)。处理这种情况的一种方法可能是在您返回的data对象中返回一个为键找到的值数组。
有关更多详细信息,请参阅此更新版本的函数中的注释:
function parseQueryString() {
// Use location.search to access query string instead
const qs = window.location.search.replace('?', '');
const items = qs.split('&');
// Consider using reduce to create the data mapping
return items.reduce((data, item) => {
const [rawKey, rawValue] = item.split('=');
const key = decodeURIComponent(rawKey);
const value = decodeURIComponent(rawValue);
// Sometimes a query string can have multiple values
// for the same key, so to factor that case in, you
// could collect an array of values for the same key
if(data[key] !== undefined) {
// If the value for this key was not previously an
// array, update it
if(!Array.isArray(data[key])) {
data[key] = [ data[key] ]
}
data[key].push(value)
}
else {
data[key] = value
}
return data
}, {})
}发布于 2018-10-24 09:04:02
您可以使用新的"URLSearchParams“-但请注意,浏览器支持并不是通用的(https://caniuse.com/#search=URLSearchParams)
var urlParams = new URLSearchParams(window.location.search);
var activeCategory, activeComponent;
// sets the active navigation if there are query paramenters in the url
if(urlParams.has('category')) {
activeCategory = urlParams.get('category');
activeComponent= urlParams.get('component');
} else {
activeCategory = null;
activeComponent= null;
}
//eg: www.myShop.com.au?category=music&component=guitar
// gives activeCategory="music" and activeComponent = "guitar"
//eg: www.myShop.com.au
// gives activeCategory = null and activeCcomponent = null发布于 2018-10-24 08:50:15
切分后,在访问索引之前,应始终检查长度,否则,如果url没有查询字符串,则会导致异常
var qsarr = window.location.href.split('?');
if(qsarr.length > 1)
var qs=qsarr[1];从循环内的项目检索值时进行相同的检查
https://stackoverflow.com/questions/52959603
复制相似问题