NodeJS urlSearchParams.getAll() 方法


URLSearchParams 类的 NodeJS urlSearchParams.getAll() 方法用于获取查询字符串中指定名称的所有值。

URLSearchParams API 提供了一些方法,这些方法可以读取和写入 URL 的查询。此类也可用于全局对象。

让我们考虑一个 YouTube URL ('https://www.youtube.com/watch?t=RSUgBMA-8Ks?t= TSUgRRMA-95'),其中 '' 之后的部分称为查询区段。在此查询中,(t) 是名称,(RSUgBMA-8Ks) 是值。它们一起形成一个名称-值对。同样,查询字符串中有两个名称-值对,它们的名称均为 (t),并且值不同。因此,如果对名称 (v) 使用 getAll() 方法,它将返回 it.

语法

以下是 NodeJS URLSearchParams.getAll() 方法的语法


 URLSearchParams.getAll(name)

参数

  • name:这指定要返回的参数的名称。

返回值

此方法返回一个数组,其中包含作为参数传递的给定名称的所有值。如果没有 name 为 name 的对,则返回空数组。

例子

如果要搜索的名称在查询字符串中多次出现,则 NodeJS urlSearchParams.getAll() 方法会将其出现的所有值以数组的形式返回。

在以下示例中,我们尝试获取查询字符串中名为 'title' 的键的所有值。


const url = require('node:url');

const MyUrl = new URL('https://www.qikepu.com/?title=1&title=2&body=3&title=4');
console.log("URL: ", MyUrl.href);

const Params = new URLSearchParams('title=1&title=2&body=3&title=4');
console.log("查询字符串:" + Params);

console.log("试图获取关键“body”的所有值.....");
console.log("该值为:" + JSON.stringify(Params.getAll("title")));

输出

正如我们在下面的输出中看到的,NodeJS getAll() 方法返回了名称 ('title') 的所有值。

URL:  https://www.qikepu.com/?title=1&title=2&body=3&title=4
查询字符串:title=1&title=2&body=3&title=4
试图获取关键“body”的所有值....
该值为: ["1","2","4"]

示例

如果要搜索的名称在查询字符串中不存在,则 getAll() 方法将返回一个空数组。

在下面的示例中,我们尝试获取名称 ('contactUs') 的值。


const url = require('node:url');

const MyUrl = new URL('https://www.qikepu.com/?title=1&header=2&body=3&footer=4');
console.log("URL: ", MyUrl.href);

const Params = new URLSearchParams('title=1&header=2&body=3&footer=4');
console.log("查询字符串: " + Params);

console.log("尝试获取密钥“contactUs”的所有值.....");
console.log("该值为: " + JSON.stringify(Params.getAll("contactUs")));

输出

getAll() 方法返回一个空数组,因为查询字符串中不存在搜索的名称。

URL:  https://www.qikepu.com/?title=1&header=2&body=3&footer=4
查询字符串: title=1&header=2&body=3&footer=4
尝试获取密钥“contactUs”的所有值.....
该值为: []