无法从url查询数组参数



如何使用URLSearchParams查找其键为数组的参数?

// Browser url:
const url = http://localhost:4000/leads?status%5B0%5D=1&page=2;
// What my code does:
const urlParams = new URLSearchParams(window.location.search);
const myParam = (urlParams.get('status%5B0%5D') || urlParams.get(key)) || "";
// Let's focus on the below myParam:
urlParams.get('status%5B0%5D') // or
urlParams.get('status[]') // or
urlParams.has('status%5B0%5D') // or
urlParams.has('status[]') // or
urlParams.getAll('status%5B0%5D') // or
urlParams.getAll('status[]')

…没有什么有用的。目的是从url中删除一个键。键可以是字符串status,也可以是数组status%5B0%5D。我在写一个函数,它可以找到键,不管它是字符串还是数组。为什么我做的任何事都没有影响?我错过什么了吗?

我看了下面的代码,没有任何效果:

// Copyright (c) Microsoft Corporation. All rights reserved.
// ...
interface URLSearchParams {
/** Appends a specified key/value pair as a new search parameter. */
append(name: string, value: string): void;
/** Deletes the given search parameter, and its associated value, from the list of all search parameters. */
delete(name: string): void;
/** Returns the first value associated to the given search parameter. */
get(name: string): string | null;
/** Returns all the values association with a given search parameter. */
getAll(name: string): string[];
/** Returns a Boolean indicating if such a search parameter exists. */
has(name: string): boolean;
/** Sets the value associated to a given search parameter to the given value. If there were several values, delete the others. */
set(name: string, value: string): void;
sort(): void;
/** Returns a string containing a query string suitable for use in a URL. Does not include the question mark. */
toString(): string;
forEach(callbackfn: (value: string, key: string, parent: URLSearchParams) => void, thisArg?: any): void;
}

看起来您必须在使用它之前解码URI

var url = new URL(decodeURI('http://localhost:4000/leads?status%5B0%5D=1&page=2;'));
console.log(url.search);
// '?status[0]=1&page=2;'
console.log(url.searchParams.get('status[0]'))
// '1'
console.log(url.searchParams.getAll('status[0]'))
// ['1']
Array.from(url.searchParams.entries()).forEach( console.log )
// ['status[0]', '1']
// ['page', '2;']

如果你可以控制URL,你可以这样写一个URL:

some-url?status=status1&status=status2&status=status3

然后你可以执行.getAll('status'),它返回一个数组。