定义一个常量,而不是重复5次



我是相当新的Node.js,我有一些问题。我在sonarqube中收到错误,因为定义了一个常量,而不是为"-deleteFlag"重复5次。如何解决这个问题?

export class CCGuid {
"-deleteFlag": string;
"#text": string;
constructor(obj: any) {
if (typeof obj === "string") {
this["#text"] = obj;
this["-deleteFlag"] = "N";
} else {
try {
this["-deleteFlag"] = obj["-deleteFlag"];
} catch {
this["-deleteFlag"] = undefined;
}
try {
this["#text"] = obj["#text"];
} catch {
this["#text"] = undefined;
}
}
}
}
export class CCGuid {
"-deleteFlag": string;
"#text": string;
constructor(obj: any) {
const deleteFlag = "-deleteFlag";
if (typeof obj === "string") {
this["#text"] = obj;
this[deleteFlag] = "N";
} else {
try {
this[deleteFlag] = obj[deleteFlag];
} catch {
this[deleteFlag] = undefined;
}
try {
this["#text"] = obj["#text"];
} catch {
this["#text"] = undefined;
}
}
}
} 

我认为这应该对SQ有用,至少在涉及到特定变量时。当然,您也可以对"#text"执行相同的操作。


编辑后:对不起,我的第一个答案是错误的,我很匆忙,没有意识到我真正写的是什么。

对于我更新的代码片段,您可以执行以下操作:

this[deleteFlag']: This will work.

this['-deleteFlag']:这当然会工作,但Sonar Qube会抱怨,因为你使用重复的字符串字面量。

this.deleteFlag:这将不起作用,因为它将在对象上查找deleteFlag键。这个键不存在,它是'-deleteFlag'

this['deleteFlag']:这在功能上与上面的行相同。将在对象上查找一个'deletFlag'键,该键不存在。

很抱歉造成混乱!希望这对你有帮助

最新更新