URLSearchParams 中没有值的参数?

Params without value in URLSearchParams?

我想要 a=1&b=2&foo URL URLSearchParams

这是我尝试过的:

new URLSearchParams([['a', 1], ['b', 2], ['foo']]).toString();
// Uncaught TypeError: Failed to construct 'URLSearchParams':
// Failed to construct 'URLSearchParams': Sequence initializer must only contain pair elements

new URLSearchParams([['a', 1], ['b', 2], ['foo', '']]).toString();
// a=1&b=2&foo=

new URLSearchParams([['a', 1], ['b', 2], ['foo', null]]).toString();
// a=1&b=2&foo=null

new URLSearchParams([['a', 1], ['b', 2], ['foo', undefined]]).toString();
// a=1&b=2&foo=undefined

能做到吗?

您可以调用 toString 并使用正则表达式删除没有值的参数后的 =

const params = new URLSearchParams([['a', 1], ['b', 2], ['foo', ''], ['bar', '']])
                .toString().replace(/=(?=&|$)/gm, '');

console.log(params)

看起来不可能。 URL 标准 says that URLSearchParams 内部具有的查询对象是 name-value 对的列表,当字符串化时,它运行 application/x-www-form-urlencoded 序列化程序,它执行:

Set encoding to the result of getting an output encoding from encoding.
Let output be the empty string.
For each tuple of tuples:
  Let name be the result of running percent-encode after encoding with encoding, tuple’s name, the application/x-www-form-urlencoded percent-encode set, and true.
  Let value be the result of running percent-encode after encoding with encoding, tuple’s value, the application/x-www-form-urlencoded percent-encode set, and true.
  If output is not the empty string, then append U+0026 (&) to output.
  Append name, followed by U+003D (=), followed by value, to output.
Return output.

由于循环中的最后一行,无论值如何,总是附加 =