如果传递给此方法的名称存在,则 URLSearchParams 类的 NodeJS urlSearchParams.has() 方法将打印 true,否则将打印 false。
URLSearchParams API 提供了一些方法,用于读取和写入 URL 的查询。此类在全局对象上也可用。
让我们看一个示例,以更好地理解 has() 方法。考虑 NETFLIX 中的“搜索引擎”,我们正在尝试在其中搜索特定电影。如果它存在,它将向您显示该特定电影,否则它会显示错误消息。
语法
以下是 NodeJS URLSearchParams.has() 方法的语法
URLSearchParams.has(name)
参数
- name:这指定了要查找的参数的名称。
返回值
此方法返回一个布尔值。
以下示例演示了 NodeJS URLSearchParams.has() 方法的用法:
例如果传递给 NodeJS urlSearchParams.has() 方法的名称存在于查询字符串中,则返回 true。
在以下示例中,我们尝试检查查询字符串中是否存在名称“header”。
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("Query string: " + Params);
console.log("The name 'header' is present in query: " + Params.has("header"));
输出
正如我们在输出中看到的,NodeJS has() 方法返回 true,因为名称“header”位于查询字符串中。
URL: https://www.qikepu.com/?title=1&header=2&body=3&footer=4
Query string: title=1&header=2&body=3&footer=4
The name 'header' is present in query: true
Query string: title=1&header=2&body=3&footer=4
The name 'header' is present in query: true
例
如果传递给 has() 方法的名称在查询字符串中不存在,则返回 false。
在下面的以下示例中,我们试图查找名称“header”是否在查询字符串中。
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("Query string: " + Params);
console.log("The name 'contactUS' is present in query: " + Params.has("ContactUS"));
输出
执行上述程序后,has() 方法返回 false,因为查询字符串中不存在已搜索的名称。
URL: https://www.qikepu.com/?title=1&header=2&body=3&footer=4
Query string: title=1&header=2&body=3&footer=4
The name 'contactUS' is present in query: false
Query string: title=1&header=2&body=3&footer=4
The name 'contactUS' is present in query: false