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

瀏覽器相容性

另見