new URLSearchParams(iterable)


  • iterable <Iterable> 元素为键值对的可迭代对象

以类似于 Map 的构造函数的方式使用可迭代映射实例化新的 URLSearchParams 对象。 iterable 可以是 Array 或任何可迭代对象。 这意味着 iterable 可以是另一个 URLSearchParams,在这种情况下,构造函数将简单地创建提供的 URLSearchParams 的克隆。 iterable 的元素是键值对,并且本身可以是任何可迭代对象。

允许重复的键。

let params;

// 使用数组
params = new URLSearchParams([
  ['user', 'abc'],
  ['query', 'first'],
  ['query', 'second']
]);
console.log(params.toString());
// 打印 'user=abc&query=first&query=second'

// 使用 Map 对象
const map = new Map();
map.set('user', 'abc');
map.set('query', 'xyz');
params = new URLSearchParams(map);
console.log(params.toString());
// 打印 'user=abc&query=xyz'

// 使用生成器函数
function* getQueryPairs() {
  yield ['user', 'abc'];
  yield ['query', 'first'];
  yield ['query', 'second'];
}
params = new URLSearchParams(getQueryPairs());
console.log(params.toString());
// 打印 'user=abc&query=first&query=second'

// 每个键值对必须恰好有两个元素
new URLSearchParams([
  ['user', 'abc', 'error']
]);
// 抛出 TypeError [ERR_INVALID_TUPLE]:
//        Each query pair must be an iterable [name, value] tuple
  • iterable <Iterable> An iterable object whose elements are key-value pairs

Instantiate a new URLSearchParams object with an iterable map in a way that is similar to Map's constructor. iterable can be an Array or any iterable object. That means iterable can be another URLSearchParams, in which case the constructor will simply create a clone of the provided URLSearchParams. Elements of iterable are key-value pairs, and can themselves be any iterable object.

Duplicate keys are allowed.

let params;

// Using an array
params = new URLSearchParams([
  ['user', 'abc'],
  ['query', 'first'],
  ['query', 'second']
]);
console.log(params.toString());
// Prints 'user=abc&query=first&query=second'

// Using a Map object
const map = new Map();
map.set('user', 'abc');
map.set('query', 'xyz');
params = new URLSearchParams(map);
console.log(params.toString());
// Prints 'user=abc&query=xyz'

// Using a generator function
function* getQueryPairs() {
  yield ['user', 'abc'];
  yield ['query', 'first'];
  yield ['query', 'second'];
}
params = new URLSearchParams(getQueryPairs());
console.log(params.toString());
// Prints 'user=abc&query=first&query=second'

// Each key-value pair must have exactly two elements
new URLSearchParams([
  ['user', 'abc', 'error']
]);
// Throws TypeError [ERR_INVALID_TUPLE]:
//        Each query pair must be an iterable [name, value] tuple