解析此URLhttp://www.domain.com/?user=rose&id=123&id=456&city=%E5%8C%97%E4%BA%AC%E5%B8%82&enabled
。将其转为对应的json。
{
user:'rose',
id:[123,456],
city:'北京市',
enabled:true
}
说明:
当然对于我们这道给了URL不需要这些。可以作为了解
url = window.location.href; /* 获取完整URL */
alert(url); /* http://127.0.0.1:8020/Test/index.html#test?name=test */
url = window.location.pathname; /* 获取文件路径(文件地址) */
alert(url); /* /Test/index.html */
url = window.location.protocol; /* 获取协议 */
alert(url); /* http */
url = window.location.host; /* 获取主机地址和端口号 */
alert(url); /* http://127.0.0.1:8020/ */
url = window.location.hostname; /* 获取主机地址 */
alert(url); /* http://127.0.0.1/ */
url = window.location.port; /* 获取端口号 */
alert(url); /* 8020 */
url = window.location.hash; /* 获取锚点(“#”后面的分段) */
alert(url); /* #test?name=test */
url = window.location.search; /* 获取属性(“?”后面的分段) */
alert(url);
url.split之后得到是按照'?'拆分的数组
let url = 'http://www.domain.com/?user=rose&id=123&id=456&city=%E5%8C%97%E4%BA%AC%E5%B8%82&enabled'
function getJson(){
let urlParam =url.split('?')[1]
return urlParam
}
let a = getJson()
console.log(a)
function getJson(){
let urlParam =url.split('?')[1]
let array = urlParam.split('&')
return array
}
// 结果如下
['user=rose', 'id=123', 'id=456', 'city=%E5%8C%97%E4%BA%AC%E5%B8%82', 'enabled']
function getJson(){
let urlParam =url.split('?')[1]
let array = urlParam.split('&')
return array.reduce((accu,str)=>{
if(str.includes('=')){
// 数组解构
let [key,value] = str.split('=')
// 中文解码
value = decodeURIComponent(value)
// 正则转为数字 为什么要使用正则?因为是在字符串中校验是否有数字
value = /^\d+$/.test(value) ? +value : value
// 如果这个键出现过
if(accu.hasOwnProperty(key)){
// 把其转为一个数组
accu[key] = [].concat(accu[key],value)
}else{
accu[key] = value
}
}else{
accu[str] = true
}
return accu
},{})
}
reduce
arr.reduce(function(prev,cur,index,arr){\
...\
}, init);
hasOwnProperty
用于检测一个属性是否是对象的自有属性
concat
合并两个/多个数组,方法不会更改现有数组,而是返回一个新数组,其中包含已连接数组的值。 此处就是合并了多个数组