Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

请编写一个 JavaScript 函数 parseQueryString,它的用途是把 URL 参数解析为一个对象,url="http://iauto360.cn/index.php?key0=0&key1=1&key2=2" #829

Open
lgwebdream opened this issue Jul 6, 2020 · 4 comments
Labels
JavaScript teach_tag 亚美科技 company 编程题 teach_tag

Comments

@lgwebdream
Copy link
Owner

No description provided.

@lgwebdream lgwebdream added JavaScript teach_tag 亚美科技 company 编程题 teach_tag labels Jul 6, 2020
@lgwebdream
Copy link
Owner Author

扫描下方二维码,获取答案以及详细解析,同时可解锁800+道前端面试题。

@GolderBrother
Copy link

const url = "http://iauto360.cn/index.php?key0=0&key1=1&key2=2";
function parseParams(url) {
  if (!url) return null;
  const paramsObj = {};
  const [, queryString] = url.split('?');
  const queryStringArr = queryString.split('&');
  for (const queryObj of queryStringArr) {
    let [key, value] = queryObj.split('=');
    value = decodeURIComponent(value);
    if (paramsObj[key]) {
      paramsObj[key] = Array.isArray(paramsObj[key]) ? paramsObj[key] : [paramsObj[key]];
      paramsObj[key].push(value);
    } else {
      paramsObj[key] = value;
    }
  }
  return paramsObj;
}
const paramsObj = parseParams(url);
console.log(paramsObj);
// { key0: '0', key1: '1', key2: '2' }

@DaphnisLi
Copy link

const main = (url) => {
  const params = url.split('?')[1]
  const paramsArr = params.split('&')
  return paramsArr.reduce((pre, cur) => {
    const curParam = cur.split('=')
    return { ...pre, [curParam[0]]: curParam[1] }
  }, {})
}

@gaohan1994
Copy link

const parseQueryString = url => {
  const [_, params] = url.split("?");
  const result = {};
  params.split("&").map(item => {
    const [key, value] = item.split("=");
    result[key] = value;
  });
  return result;
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
JavaScript teach_tag 亚美科技 company 编程题 teach_tag
Projects
None yet
Development

No branches or pull requests

4 participants