URLSearchParams 类的 NodeJS urlSearchParams.values() 方法返回一个 ES6 迭代器,该迭代器允许迭代每个名称-值对的所有值。
让我们考虑一个 YouTube URL ('https://www.youtube.com/watch?z=HY4&z=NJ7),其中 '?' 后面的部分称为查询段。在此查询中,(z) 是名称,(HY4) 是值。它共同构成了一个名称-值对。
查询字符串中有两个名称/值对。因此,如果我们将查询字符串分配给 values() 方法,它会在每个名称-值对的值上返回一个 ES6 迭代器。
URLSearchParams API 提供了一些方法,这些方法提供了读取和写入 URL 查询的访问权限。此类在全局对象上也可用。
语法
以下是 NodeJS URLSearchParams.values() 方法的语法
URLSearchParams.values()
参数
此方法不接受任何参数。
返回值
此方法在每个名称/值对的值上返回一个 ES6 迭代器。
以下示例演示了 NodeJS URLSearchParams.values() 方法的用法:
例如果输入 URL 字符串包含查询段,则 NodeJS urlSearchParams.values() 方法将返回一个迭代器,该迭代器将覆盖查询字符串中名称-值对的所有值。
在以下示例中,我们尝试从查询字符串的名称-值对中获取所有值。
const url = require('node:url');
const MyUrl = new URL('https://www.qikepu.com?1=one&3=three&6=six&9=nine');
console.log("URL: ", MyUrl.href);
const Params = new URLSearchParams('1=one&3=three&6=six&9=nine');
console.log("Query string: " + Params);
console.log('All the values in the query string are: ');
for (const value of Params.values()) {
console.log(value);
}
输出
正如我们在下面的输出中看到的,NodeJS values() 方法返回名称-值对中的所有值。
URL: https://www.qikepu.com/?1=one&3=three&6=six&9=nine
Query string: 1=one&3=three&6=six&9=nine
All the values in the query string are:
one
three
six
nine
Query string: 1=one&3=three&6=six&9=nine
All the values in the query string are:
one
three
six
nine
例
在以下示例中,我们将一些名称/值对追加到输入查询字符串中。然后,我们尝试从名称-值对中获取值。
const url = require('node:url');
const Params = new URLSearchParams('1=one&3=three&6=six&9=nine');
console.log("Query string: " + Params);
Params.append(12, 'twelve');
Params.append(15, 'fifteen');
console.log('All the values in the query string are: ');
for (const value of Params.values()) {
console.log(value);
}
输出
在执行上述程序时,它将生成以下输出
Query string: 1=one&3=three&6=six&9=nine
All the values in the query string are:
one
three
six
nine
twelve
fifteen
All the values in the query string are:
one
three
six
nine
twelve
fifteen