解题思路
String.prototype.match()方法检索匹配正则表达式,以获取所有键值对。- 用
Array.prototype.reduce()将它们映射并组合成一个对象。 - 作为参数传递
location.search以应用于当前url。(未使用)
Javascript
精简
const getURLParameters = url =>
(url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce(
(total, currentValue) => (
(total[currentValue.slice(0, currentValue.indexOf('='))] = currentValue.slice(currentValue.indexOf('=') + 1)), total
),
{}
);
分解
// 略微复杂 不太理解reduce😭
const reduceFn= (total, currentValue) => {
// 这里的return 没搞明白
return (
(total[currentValue.slice(0, currentValue.indexOf('='))] = currentValue.slice(currentValue.indexOf('=') + 1)), total
)
}
const getURLParameters = url => (url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce(reduceFn,{})
使用举例
getURLParameters('google.com');
// {}
getURLParameters('http://url.com/page?name=Adam&surname=Smith');
// {name: 'Adam', surname: 'Smith'}
// (url.match(/([^?=&]+)(=([^&]*))/g) || []) 结果为["name=Adam","surname=Smith"]
reduce()
定义和使用
reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。 reduce() 可以作为一个高阶函数,用于函数的 compose。
注意: reduce() 对于空数组是不会执行回调函数的。
语法
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
total:必需。初始值, 或者计算结束后的返回值。currentValue:必需。当前元素。currentIndex:可选。当前元素的索引arr:必需。可选, 当前元素所属的数组对象。initialValue:可选。传递给函数的初始值。
window.location
| 属性 | 描述 |
|---|---|
| hash | 从井号 (#) 开始的 URL(锚) |
| host | 主机名和当前 URL 的端口号 |
| hostname | 当前 URL 的主机名 |
| href | 完整的 URL |
| pathname | 当前 URL 的路径部分 |
| port | 当前 URL 的端口号 |
| protocol | 当前 URL 的协议 |
| search | 从问号 (?) 开始的 URL(查询部分) |