[英]How to dynamically form Constant string in Javascript and Typescript
我在 Typescript 中有一個常量類,它有以下內容。
export class Constants {
public static readonly SERVER_1: string = "server url 1";
public static readonly SERVER_2: string = "server url 2";
public static readonly SERVER_3: string = "server url 3";
.....
public static readonly SERVER_21: string = "server url 21";
}
在我的 Processor 類中,我需要形成對象,然后推送到這樣的數組進行處理。
export class Processor {
public areReachable(): void {
const myObject1: ServerReachObject1 = new ServerReachObject(Constants.SERVER_1);
const myObject2: ServerReachObject2 = new ServerReachObject(Constants.SERVER_2);
const myObject3: ServerReachObject3 = new ServerReachObject(Constants.SERVER_3);
.....
const myObject21: ServerReachObject21 = new ServerReachObject(Constants.SERVER_21);
const sModelArray: DNSServerModelInfo[] = [];
ftpModelServerArray.push(myObject1, myObject2, myObject3 ..... myObject21);
}
}
有沒有更好的方法來寫上面的。 將來,可能會添加服務器。 我的資深團隊成員建議我以更好的方式寫作。 請建議我並幫助我。
我試着這樣寫。
for (let i = 1; i < 22; i++) {
const dynamicServerName = Constants + ".SERVER_"+i;
const myObject1: ServerReachObject = new ServerReachObject(dynamicServerName);
const sModelArray: DNSServerModelInfo[] = [];
ftpModelServerArray.push(sModelArray);
}
但它不起作用。 我的目標是從 Constant 類動態地形成字符串,而不是一一手動聲明。 請幫我。
請考慮使用 const 對象而不是具有 const 字段的類。 然后,您可以使用Object.values()
迭代服務器 url 值。
type ServerConstants = {
readonly [name: string]: string;
}
export const Server: ServerConstants = {
SERVER_1: 'Server url 1',
SERVER_2: 'Server url 2'
}
Server.SERVER_1 = 'foo'; // throws error correctly because of readonly in ServerConstants type
Object.values(Server).forEach(value => console.log(value));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.