有没有办法在打字稿中的VAR中循环?
setup() {
var nodes = {
node1: { name: "Node 1" },
node2: { name: "Node 2" },
node3: { name: "Node 3" },
node4: { name: "Node 4" },
}
var edges = {
edge1: { source: "node1", target: "node2" },
edge2: { source: "node2", target: "node3" },
edge3: { source: "node3", target: "node4" },
}
return { nodes, edges }
}
因此,与其编写Node1,node2等,等等,我有没有办法循环并创建完全相同的东西? 任何建议将被赞赏。
setup() {
var nodes = {
node1: { name: "Node 1" },
node2: { name: "Node 2" },
node3: { name: "Node 3" },
node4: { name: "Node 4" },
}
var edges = {
edge1: { source: "node1", target: "node2" },
edge2: { source: "node2", target: "node3" },
edge3: { source: "node3", target: "node4" },
}
return { nodes, edges }
}
So instead of writing node1,node2, and so on, is there a way I can loop and create the exact same thing?
Any suggestions are appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这是一个解决方案:
Here's a solution:
是的。您可以使用“ nofollow noreferrer”> .fromentries 。
object.fromentries
从一系列条目创建一个对象,其中“条目”是一个具有两个元素的数组:属性名称和该属性的值。这是一个示例,可以重新创建您的数据:
Yes. You can dynamically create property names using something like Object.fromEntries.
Object.fromEntries
creates an object from a series of entries, where an "entry" is an array with two elements: a property name, and a value for that property.Here's an example that recreates your data above:
确定可以!许多方式,一种常见的方法是:
Sure you can! Many ways, one of the common ones is:
以下代码具有相同的结果,但使用for-loops,如果您需要其他内容,请在问题中更具体。
The following code has the same result but uses for-loops, please be more specific in your question if you need something else.
尝试一下(我只是添加了一个逻辑来生成对象):
Try this (I just added a logic to generate the objects) :