class a {
public COUNTS = new Set<string>();
constructor() {
}
public execute(): any {
this.COUNTS.add('a');
this.COUNTS.add('b');
console.log(this.COUNTS);
return { contas: this.COUNTS };
}
}
const x = (new a()).execute();
console.log(x);
第一个控制台日志返回按预期创建的集合,但第二个控制台日志仅返回 { contas: {} }。我想知道为什么这只发生在 SET 和 MAP 中。
最佳答案
这里没有什么问题。您所看到的是您正在使用的工具如何决定表示其输出。
在 TS Playground 中,您会看到以下内容:
但是如果您从那里获取编译后的 JavaScript 代码并将其放入 StackOverflow 的代码片段中,您会看到以下内容:
class a {
constructor() {
this.COUNTS = new Set();
}
execute() {
this.COUNTS.add('a');
this.COUNTS.add('b');
console.log(this.COUNTS);
return { contas: this.COUNTS };
}
}
const x = (new a()).execute();
console.log(x);
但是如果您打开 Chrome 开发工具并查看控制台输出,您会看到以下内容:
因此,不同的工具在控制台输出中以不同的方式表示 Set,并且当 Set 位于 JavaScript 对象内部时,其中一些工具会更改该表示形式。无论如何,该集合应该继续像集合一样工作。
如果您要构建此对象以作为 JSON 字符串发送,请注意 Set 对象的 JSON 表示形式就是 {}
。因此,您可能需要将其转换为可序列化的内容,例如数组,您可以使用扩展运算符来完成此操作:
return { contas: [...this.COUNTS] };
关于javascript - 具有 Set 集合的类方法不返回任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76773784/