在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认为它期望类方法使用它,并且它期望箭头函数中有一个返回值。
发布于 2017-05-29 12:52:01
当您不关心返回值时,不需要使用.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;
https://stackoverflow.com/questions/44242964
复制相似问题