实现说明
顶层就这几处状态:query、other。
使用要点
- 包管理器在这个示例里从头到尾都不出场。
- 演示输出是带标签的(
canonical:、tag order:、same canonical key:),每个操作都会留下自己的一行标注。
常见问题
安装包是准备工作的一部分吗?
不需要。只用内建 API,安装这一步可以省掉。 状态都挂在模块顶层:query、other。
核心语句
query.sort();
other.sort();
代码示例
const query = new URLSearchParams('sort=desc&tag=es2024&page=2&tag=intl&A=1');
// sort() mutates in place using UTF-16 code unit order (uppercase 'A' precedes 'page')
query.sort();
console.log('canonical:', query.toString());
// Duplicate keys preserve their original relative insertion order ('es2024' before 'intl')
console.log('tag order:', JSON.stringify(query.getAll('tag')));
// Compare two differently ordered queries after sorting both
const other = new URLSearchParams('page=2&tag=es2024&A=1&tag=intl&sort=desc');
other.sort();
console.log('same canonical key:', query.toString() === other.toString());