我需要循环使用多个数组。
下面是我编写的代码,如何避免多个forEach。
@Input() content: any;
public sections:any;
ngOnInit() {
this.content.forEach(content => {
content.block.forEach(response => {
this.service.createComponent(response, type);
});
});
}
如何减少上述行并提高代码质量?
首先,array.map
不是为了循环。这是array.forEach
的工作。 array.map
用于从另一个数组创建一个数组,可选地转换每个值。
this.content.map(data => this.sections = data.sections);
这样做是将this.content
中的最后一项分配给this.sections
。你不需要array.map
这样做。您只需通过其索引获取最后一项。
this.sections = this.content[this.content.length - 1]
如果您的数据是嵌套的,则无法避免多个循环。但是,为提高可读性,您可以做的是将嵌套循环转换为一系列平坦的循环。在你的代码中,你所追求的是response
。所以让我们首先压扁this.sections
然后循环它。
this.sections
.map(rjfBlock => rjfBlock.rjf)
.reduce((c, rjf) => [...c, ...rjf], [])
.forEach(response => {
const type = this.contentMappings[response.type]
this.service.createComponent(response, type)
})
让我们打破这个:
.map
将所有rjf
数组收集到一个数组中。此时,我们有一个数组数组。.reduce
通过将每个数组合并为一个数组来展平数组。此时,我们有一个一级响应。.forEach
- 循环每个响应。