
JavaScript URLSearchParams 获取查询字符串
在本教程中,您将学习如何使用 JavaScript 的 URLSearchParams 获取查询字符串参数
在本教程中,您将学习如何使用 JavaScript 的 URLSearchParams 获取查询字符串参数。
要获取查询字符串,您可以访问 location 对象的 search 属性:
location.search假设 location.search 的值为:
'?type=list&page=20'要使用查询字符串,您可以使用 URLSearchParams 对象。
const urlParams = new URLSearchParams(location.search);
URLSearchParams 是一个可迭代对象,因此您可以使用 for...of 循环来迭代其作为查询字符串参数的元素:
const urlParams = new URLSearchParams(location.search);
for (const [key, value] of urlParams) {
console.log(`${key}:${value}`);
}输出:
type:list
page:20URLSearchParams 对象的方法
URLSearchParams 有一些常用的方法可以返回键、值和键值对的迭代器:
keys()返回一个迭代器,该迭代器迭代参数的键。values()返回一个迭代器,该迭代器迭代参数的值。entries()返回一个迭代器,该迭代器迭代参数的(键,值)对。
keys 方法迭代所有键
下面的示例使用 keys() 方法列出查询字符串的所有参数名称:
const urlParams = new URLSearchParams('?type=list&page=20');
for (const key of urlParams.keys()) {
console.log(key);
}输出:
type
pagevalues 方法迭代所有值
下面的示例使用 values() 方法列出查询字符串的所有值:
const urlParams = new URLSearchParams('?type=list&page=20');
for (const value of urlParams.values()) {
console.log(value);
}
输出:
list
20entries 方法迭代所有键值对
下面的示例使用 entries() 方法列出查询字符串的所有参数键值对:
const urlParams = new URLSearchParams('?type=list&page=20');
for (const entry of urlParams.entries()) {
console.log(entry);
}输出:
["type", "list"]
["page", "20"]has 方法检查指定键是否存在
如果具有指定名称的参数存在,则 URLSearchParams.has() 方法返回 true。
const urlParams = new URLSearchParams('?type=list&page=20');
console.log(urlParams.has('type')); // true
console.log(urlParams.has('foo')); // false输出:
true
false结论
URLSearchParams 提供一个使用查询字符串参数的接口,URLSearchParams 返回一个可迭代的对象,因此您可以使用 for...of 循环来迭代查询字符串参数。











