如何使用 找到鍵為陣列的引數URLSearchParams?
// Browser url:
const url = http://localhost:4000/leads?status[0]=1&page=2;
// What my code does:
const urlParams = new URLSearchParams(window.location.search);
const myParam = (urlParams.get('status[0]') || urlParams.get(key)) || "";
// Let's focus on the below myParam:
urlParams.get('status[0]') // or
urlParams.get('status[]') // or
urlParams.has('status[0]') // or
urlParams.has('status[]') // or
urlParams.getAll('status[0]') // or
urlParams.getAll('status[]')
……沒有什么用處。目的是從 url 中洗掉一個鍵。鍵可以是字串,也可以是status陣列status[0]。我正在撰寫一個可以找到鍵的函式,無論它是字串還是陣列。為什么我做什么都沒有影響?我錯過了什么嗎?
我查看了以下內容,但沒有任何效果:
// 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;
}
uj5u.com熱心網友回復:
看起來您必須在使用 URI 之前對其進行解碼
var url = new URL(decodeURI('http://localhost:4000/leads?status[0]=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;']
uj5u.com熱心網友回復:
如果您能夠控制 URL,則可以撰寫如下 URL:
some-url?status=status1&status=status2&status=status3
然后你可以做.getAll('status')which 回傳一個陣列。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/471238.html
標籤:javascript
下一篇:SFINAE在遞回函式中不起作用
