此函数返回与参数中传递的名称匹配的第一个名称-值对。如果不存在这样的值,则返回 null。如果存在多个名称-值对,它将返回该元素在 URL 中的第一次出现。
URLSearchParams.get(name);
它将返回与作为函数参数传递的名称匹配的单个字符串。如果不存在对,则返回 null。
// 将 URL 定义为常量 const myURL = new URL( 'https://example.org/?firstName=John&firstName=Mark'); // Printing all the params that match value -> 'firstName' console.log(myURL.searchParams.get('firstName'));
John
// 将 URL 定义为常量 const myURL = new URL( 'https://example.org/?firstName=John&firstName=Mark'); // Printing all the params that match value -> 'lastName' console.log(myURL.searchParams.getAll('lastName'));
null
此函数返回与给定参数匹配的所有值。如果不存在这样的对,则返回 null。如果存在多个名称-值对,它将以数组格式返回该元素的所有出现。
URLSearchParams.getAll(name);
它将返回一个字符串数组,其名称-值对与在函数中作为参数传递的名称相匹配。如果不存在对,它将返回一个空数组。
// 将 URL 定义为常量 const myURL = new URL( 'https://example.org/?firstName=John&firstName=Mark'); // Printing all the params that match value -> 'firstName' console.log(myURL.searchParams.getAll('firstName'));
['John', 'Mark']
// 将 URL 定义为常量 const myURL = new URL( 'https://example.org/?Id=2&Id=3&Id=7'); // Printing all the params that match value -> 'Id' console.log(myURL.searchParams.getAll('Id'));
['2', '3', '7']
注– 支持所有现代浏览器。