面试题:提取 URL 中的各个 GET 参数

317 阅读1分钟

有这样一个URL:item.taobao.com/item.htm?a=…

  • 请写一段 JS 程序提取 URL 中的各个 GET 参数(参数名和参数个数不确定),
  • 将其按key - value 形式返回到一个 json 结构中,
  • 如{ a: "1", b: "2", c: "", d: "xxx", e: undefined }(必会)
    let url = 'http://item.taobao.com/item.htm?a=1&b=2&c=&d=xxx&e';
    // split() 是 string 的方法,返回一个数组,数组中的元素是字符串的分割结果(必会)
    let arr = url.split('?');
    let obj = {};
    let arr1 = arr[1].split('&');
    for (let i = 0; i < arr1.length; i++) {
      let arr2 = arr1[i].split('=');
      console.log(arr2);
      obj[arr2[0]] = arr2[1];
    }
    console.log(obj);