/** * 兼容小程序 */ class MyURLSearchParams { params: {} constructor(init) { this.params = {} if (typeof init === 'string') { this.parse(init) } else if (init && typeof init === 'object') { // eslint-disable-next-line no-restricted-syntax for (const key in init) { if (Object.prototype.hasOwnProperty.call(init, key)) { this.append(key, init[key]) } } } } // 解析查询字符串 parse(str) { const params = str.split('&') params.forEach((param) => { const [key, value] = param.split('=').map(decodeURIComponent) this.append(key, value) }) } // 添加参数 append(key, value) { if (this.params[key]) { this.params[key] = this.params[key].concat([value]) } else { this.params[key] = [value] } } // 获取参数值(单个值) get(key) { return this.params[key] ? this.params[key][0] : null } // 获取参数值(所有值) getAll(key) { return this.params[key] || [] } // 删除参数 delete(key) { delete this.params[key] } // 检查参数是否存在 has(key) { return Object.prototype.hasOwnProperty.call(this.params, key) } // 设置参数值 set(key, value) { this.params[key] = [value] } // 返回查询字符串 toString() { const items = [] // eslint-disable-next-line no-restricted-syntax for (const key in this.params) { if (Object.prototype.hasOwnProperty.call(this.params, key)) { this.params[key].forEach((value) => { items.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`) }) } } return items.join('&') } } export default MyURLSearchParams