如果foreach内的/ else条件

Mat*_*Mat 0 javascript typescript angular

我正在开发一个有角度的项目。我有一个表文件,我想将每个元素与一个数据值进行比较(如果正确),我会做声明,否则我会做另一个比较,但是我的问题是,即使数据正确,它也总是会获取所有表,并且应该在其他很短的时间。请如何避免这种情况。

这是我的代码:

if (this.data) {
  this.imgNotFoundText = '';
  this.data.package.files.forEach(element => {
    i++;
    this.picture = '';
    if (element.name == this.data.properties.Name) {
      this.picture = 'picOne.png'
    }
    if (i == this.data.package.files.length && this.picture == '') {
      this.picture = './../assets/img/notFound.jpg'
    }
  });
}
Run Code Online (Sandbox Code Playgroud)

T.J*_*der 5

我看到几个可能的问题:

  1. 似乎总是this.picture = '';在循环中无条件地执行操作。如果要执行此操作,则最好只查看数组中的最后一个条目。你可能想以移动到forEach通话。

  2. 您已经提到了else,但是else代码中没有。您if连续有两个,但是第一个的结果对第二个if没有任何影响。您可能想要过else if。然后,if如果第一个条件if为true,则不执行第二个。

因此,如果这些猜测都正确:

if (this.data) {
    this.imgNotFoundText = '';
    this.picture = '';
    this.data.package.files.forEach(element => {
        i++;
        if (element.name == this.data.properties.Name) {
            this.picture = 'picOne.png'
        } else if (i == this.data.package.files.length && this.picture == '') {
            this.picture = './../assets/img/notFound.jpg'
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

旁注:您尚未显示如何i进行初始化,但是如果使用它来跟踪的当前条目的索引forEach,则无需:将forEach其作为第二个参数接收:

if (this.data) {
    this.imgNotFoundText = '';
    this.picture = '';
    this.data.package.files.forEach((element, index) => {
    // -----------------------------^^^^^^^^^^^^^^^^
        if (element.name == this.data.properties.Name) {
            this.picture = 'picOne.png'
        } else if (index == this.data.package.files.length && this.picture == '') {
    // ------------^^^^^
            this.picture = './../assets/img/notFound.jpg'
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

您可能还希望if通过在循环之前指定默认值“ not found”来完全避免第二次:

if (this.data) {
    this.imgNotFoundText = '';
    const {files} = this.data.package;
    this.picture = files.length ? './../assets/img/notFound.jpg' : '';
    files.forEach(element => {
        if (element.name == this.data.properties.Name) {
            this.picture = 'picOne.png'
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我假设this.picture应该是''中没有任何条目files,或者如果至少有一个条目则是“未找到”图像。如果找到匹配项,循环将覆盖它。

从那里继续,除非有多个files相同的条目,否则name您可能要在第一个匹配项之前停止。所以:

if (this.data) {
    this.imgNotFoundText = '';
    const {files} = this.data.package;
    this.picture = files.length ? './../assets/img/notFound.jpg' : '';
    for (const {name} of files) {
        if (name == this.data.properties.Name) {
            this.picture = 'picOne.png'
            break;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)