new URLSearchParams(obj)


  • obj <Object> 一个表示键值对集合的对象

通过使用查询哈希映射实例化一个新的URLSearchParams对象, obj的每一个属性的键和值将被强制转换为字符串。

请注意: 和 querystring 模块不同的是, 在数组的形式中,重复的键是不允许的。数组使用array.toString()进行字符串化时,只需用逗号连接所有的数组元素即可。

const { URLSearchParams } = require('url');
const params = new URLSearchParams({
  user: 'abc',
  query: ['first', 'second']
});
console.log(params.getAll('query'));
  // 输出 [ 'first,second' ]
console.log(params.toString());
  // 输出 'user=abc&query=first%2Csecond'
  • obj <Object> An object representing a collection of key-value pairs

Instantiate a new URLSearchParams object with a query hash map. The key and value of each property of obj are always coerced to strings.

Unlike querystring module, duplicate keys in the form of array values are not allowed. Arrays are stringified using array.toString(), which simply joins all array elements with commas.

const params = new URLSearchParams({
  user: 'abc',
  query: ['first', 'second']
});
console.log(params.getAll('query'));
// Prints [ 'first,second' ]
console.log(params.toString());
// Prints 'user=abc&query=first%2Csecond'