URLSearchParams:size 属性

备注: 此特性在 Web Worker 中可用。

URLSearchParams 接口的 size 只读属性表示查询参数条目的总数。

一个数字,表示 URLSearchParams 对象的查询参数条目的总数。

示例

获取查询参数条目的数量

你可以像这样获取查询参数条目的总数:

js
const searchParams = new URLSearchParams("c=4&a=2&b=3&a=1");
searchParams.size; // 4

请注意参数 a 出现了两次,但是 size 返回的数值是 4 不是 3。要获取唯一键的数量,你可以使用 Set,例如:

js
[...new Set(searchParams.keys())].length; // 3

检查查询参数是否存在

size 属性用于检查是否存在任何查询参数:

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

if (url.searchParams.size) {
  console.log("URL 具有查询参数!");
}

规范

Specification
URL
# dom-urlsearchparams-size

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobileserver
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
Deno
Node.js
size

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
No support
No support
Has more compatibility info.

参见