在 ES6 中提取查询字符串的正确方法是什么?
我写了这个函数:
getUrlParams(queryString) {
const hashes = queryString.slice(queryString.indexOf('?') + 1).split('&');
const params = {};
hashes.map((hash) => {
const [key, val] = hash.split('=');
params[key] = decodeURIComponent(val);
});
return params;
}
然而,ESLint 认为它希望 this 被类方法使用,并且它希望在箭头函数中有一个返回值。
最佳答案
当你不关心返回值时,你不需要使用.map
;使用 .forEach
代替:
hashes.forEach(hash => {
const [key, val] = hash.split('=');
params[key] = decodeURIComponent(val);
});
看,.map
函数通常期望返回一个新集合(其中每个项目代表与原始集合的项目的某种关系)。
事实上,您可以使用 .reduce()
简化它:
const params = hashes.reduce((params, hash) => {
const [key, val] = hash.split('=');
params[key] = decodeURIComponent(val);
return params;
}, {});
return params;
关于javascript - 提取 URL 查询字符串 ES6,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44242964/