URLSearchParams: has() 方法

Baseline 广泛可用 *

此功能已成熟,可跨多种设备和浏览器版本工作。它自 ⁨2018 年 4 月⁩ 起已在所有浏览器中可用。

* 此特性的某些部分可能存在不同级别的支持。

注意:此功能在 Web Workers 中可用。

has() 方法是 URLSearchParams 接口的一部分,它返回一个布尔值,表示指定的参数是否存在于搜索参数中。

可以通过参数名称和可选的值来匹配参数。如果只指定了参数名称,则当查询字符串中的任何参数匹配该名称时,该方法将返回 true,否则返回 false。如果同时指定了参数名称和值,则当参数同时匹配名称和值时,该方法将返回 true

语法

js
has(name)
has(name, value)

参数

name

要匹配的参数名称。

value

要匹配的参数值,以及给定的参数名称。

返回值

一个布尔值。

示例

检查具有指定名称的参数

此示例说明了如何检查查询字符串是否包含具有特定名称的任何参数。

js
const url = new URL("https://example.com?foo=1&bar=2&foo=3");
const params = new URLSearchParams(url.search);

// has() returns true if the parameter is in the query string
console.log(`bar?:\t${params.has("bar")}`);
console.log(`bark?:\t${params.has("bark")}`);
console.log(`foo?:\t${params.has("foo")}`);

下面的日志显示参数 barbarkfoo 是否存在于查询字符串中。

bar?:  true
bark?: false
foo?:  true

检查具有指定名称和值的参数

此示例说明了如何检查查询字符串是否包含同时匹配特定名称和值的参数。

js
const url = new URL("https://example.com?foo=1&bar=2&foo=3");
const params = new URLSearchParams(url.search);

// has() returns true if a parameter with the matching name and value is in the query string
console.log(`bar=1?:\t${params.has("bar", "1")}`);
console.log(`bar=2?:\t${params.has("bar", "2")}`);
console.log(`foo=4?:\t${params.has("foo", "4")}`);

只有上面的第二个值应为 true,因为只匹配了值为 2 的参数名称 bar

bar=1?: false
bar=2?: true
foo=4?: false

如果您的浏览器不支持 value 选项,该方法将仅匹配名称,所有结果应为 true

规范

规范
URL
# dom-urlsearchparams-has

浏览器兼容性

另见