'''js
function getUrlParams(key) { let queryString = ''
const href = window.location.href const hashIndex = href.indexOf('#') const queryIndex = href.indexOf('?')
if (hashIndex !== -1 && href.includes('?#')) { // hash 模式,形如 a.com/#/?id=1 const hashQueryIndex = href.indexOf('?', hashIndex) queryString = href.slice(hashQueryIndex + 1) } else if (hashIndex !== -1 && href[hashIndex + 1] === '?') { // hash 模式,?# 开头 queryString = href.slice(hashIndex + 2) } else if (queryIndex !== -1) { // 普通模式 queryString = href.slice(queryIndex + 1).split('#')[0] }
if (!queryString) return key ? null : {}
const pairs = queryString.split('&') const result = {}
for (const pair of pairs) { if (!pair) continue const [rawKey, rawValue] = pair.split('=') if (!rawKey) continue
const k = decodeURIComponent(rawKey.trim())
const v = rawValue !== undefined ? decodeURIComponent(rawValue.trim()) : null
if (result[k] !== undefined) {
result[k] = Array.isArray(result[k]) ? [...result[k], v] : [result[k], v]
} else {
result[k] = v
}
}
return key ? (result.hasOwnProperty(key) ? result[key] : null) : result }
'''