解题思路:
- 获取参数字符串,即取得 "?" 与 "#" 之间的字符串
- 将参数字符串作为键值对存储起来
- 特殊情况判断返回
- 判断 指定 与 不指定 参数名称两种返回结果
- 判断 不指定 参数时 有结果 旧返回,无结果 返回空字符串
''
完整代码
// 1. 获取参数字符串,即取得 "?" 与 "#" 之间的字符串
const result = {}
sUrl.match(/\?(.*)\#/)[1].split('&').forEach(item => {
// 2. 将参数字符串作为键值对存储起来
const tempArr = item.split('=')
result[tempArr[0]] = !result.hasOwnProperty(tempArr[0]) ?
tempArr[1] : Array.isArray(result[tempArr[0]]) ?
[...result[tempArr[0]], tempArr[1]] : [result[tempArr[0]], tempArr[1]]
})
// 3. 特殊情况判断返回
return sKey ? result[sKey] || '' : result解惑:result[tempArr[0]] = !result.hasOwnProperty(tempArr[0]) ? tempArr[1] : Array.isArray(result[tempArr[0]]) ? [...result[tempArr[0]], tempArr[1]] : [result[tempArr[0]], tempArr[1]]
这里面中:[...result[tempArr[0]], tempArr[1]] 意思是当 result[tempArr[0]] 是数组时将 ...result[tempArr[0]] 解构,同时与最新获得 tempArr[1] 合并成一个新的数组,即 [...result[tempArr[0]], tempArr[1]]。
举个例子:
result[tempArr[0]] = [1, 2] tempArr[1] = 3 [...result[tempArr[0]]] = [1,2] [...result[tempArr[0]], tempArr[1]] = [1, 2, 3]

京公网安备 11010502036488号