如何解决URLSearchParams.set赋值后返回undefined的问题?
精简URL参数修改代码并内联到onclick的方法
问题说明
原代码用于修改URL的order参数并跳转:
const urlParams = new URLSearchParams(window.location.search); urlParams.set('order', 'dates'); window.location.search = urlParams;
尝试简化时写成了下面的错误写法,导致页面跳转到/?undefined:
window.location.search = (new URLSearchParams(window.location.search)).set('order', 'dates');
原因是URLSearchParams.set()方法的返回值是undefined,而非修改后的参数对象,所以赋值后会得到undefined作为搜索参数。
以下是几种可以精简代码并安全内联到HTMLonclick属性的方法:
方法1:使用逗号运算符
逗号运算符会依次执行多个表达式,返回最后一个表达式的结果。我们可以先执行set操作,再返回修改后的URLSearchParams对象:
window.location.search = (p => (p.set('order', 'dates'), p))(new URLSearchParams(location.search))
内联到HTML的写法:
<button onclick="window.location.search=(p=>(p.set('order','dates'),p))(new URLSearchParams(location.search))">按日期排序</button>
方法2:使用Object.assign
利用Object.assign将新参数直接合并到新建的URLSearchParams对象中,这种写法更简洁:
window.location.search = Object.assign(new URLSearchParams(location.search), { order: 'dates' })
内联到HTML的写法:
<button onclick="window.location.search=Object.assign(new URLSearchParams(location.search),{order:'dates'})">按日期排序</button>
方法3:直接拼接参数(仅适用于简单场景)
如果确定页面原本没有order参数,或者不需要保留其他搜索参数,可以直接拼接字符串,但这种方法会导致重复参数(如果原URL已有order),仅推荐简单场景使用:
window.location.search = `${location.search ? location.search + '&' : '?'}order=dates`
内联到HTML的写法:
<button onclick="window.location.search=`${location.search?location.search+'&':'?'}order=dates`">按日期排序</button>
内容的提问来源于stack exchange,提问作者Daniel
相关产品推荐
相关产品推荐

