URLSearchParams:forEach() 方法

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

We’d love to hear your thoughts on the next set of proposals for the JavaScript language. You can find a description of the proposals here.
Please take two minutes to fill out our short survey.

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

URLSearchParams 接口的 forEach() 方法允许通过回调函数来遍历实例对象上的键值对。

语法

js
forEach(callback)
forEach(callback, thisArg)

参数

callback

在每个元素上执行的函数,会传入以下参数:

value

URLSearchParams 对象中正在处理的条目的值。

key

URLSearchParams 对象中正在处理的条目的键。

searchParams

当前调用 forEach() 方法的 URLSearchParams 对象。

thisArg 可选

执行 callbackthis 的值。

返回值

无(undefined)。

示例

js
// 创建用于测试的 URLSearchParams 对象
const searchParams = new URLSearchParams("key1=value1&key2=value2");

// 输出值
searchParams.forEach((value, key) => {
  console.log(value, key);
});

结果是:

value1 key1
value2 key2

规范

Specification
URL
# dom-urlsearchparams-urlsearchparams

浏览器兼容性

参见

  • URL 接口。