这是JavaScript代码,工作非常完美,但问题是我无法理解这是如何工作的。如果有人知道这是怎么回事,请解释给我听。
这是查询= ?cid=619386618c57a571f4463d45&type=page
export default (query) => {
if(query){
const queryString = query.split("?")[1];
if(queryString.length > 0){
const params = queryString.split("&");
const paramObj = {};
params.forEach(param => {
const keyValue = param.split("=");
paramObj[keyValue[0]] = keyValue[1];
});
return paramObj;
}
}
return {};
}
发布于 2022-01-23 22:49:04
这里几乎没有反应。这是相当普通的JavaScript
export default (query) => { // this is the only react here
if(query){ // if there is a string
const queryString = query.split("?")[1]; // get the stuff after the ?
if(queryString.length > 0){ // if there was stuff after the ?
const params = queryString.split("&"); // split on & (gives an array)
const paramObj = {}; // create an object
params.forEach(param => { // for each part of the split array
const keyValue = param.split("="); // split on the =
paramObj[keyValue[0]] = keyValue[1]; // use the string before the = as key and after as value
});
return paramObj; // return the object
}
}
return {}; // otherwise return empty object
}
整件事都可以写下来
export default (query) => {
let urlParams = new URLSearchParams(query);
const result = {};
for (const [key, value] of urlParams.entries()) {
result[key] = value;
}
return result;
}
测试:
const getParams = query => {
let urlParams = new URLSearchParams(query);
const result = {}
for (const [key, value] of urlParams.entries()) { // each 'entry' is a [key, value] tupple
result[key] = value;
}
return result;
}
console.log(getParams("?cid=619386618c57a571f4463d45&type=page"))
https://stackoverflow.com/questions/70829927
复制