使用角度7中的打字稿,找到至少一个与数组中的条件匹配的元素

时间:2019-07-11 14:27:45

标签: angular

我基本上需要使用角度7中的打字稿来搜索数组中值true的任何出现。

如果您在this.DocumentSelected[i] = true;下注意到是否满足条件。理想情况下,我想退出这里,但返回无效 在地图内。因此,我试图初始化数组,并检查是否有一个包含true的值,然后退出该方法。

DocumentSelected: any = [];

this.files.map(doc => {
  if (doc.selectedDocumentItem.Id === null) {
    this.DocumentSelected[i] = true;
    return;
  }

  const datestr = (new Date(doc.selectedDate)).toUTCString();

  formData.append('documentTypeId' + i++, doc.selectedDocumentItem.Id.toString());
  formData.append('documentDate' + j++, datestr);

  const fileEntry = doc.fileDropEntry.fileEntry as FileSystemFileEntry;

  fileEntry.file((file: File) => {
    formData.append('file' + k++, file, doc.name);
  });
});

if (this.DocumentSelected) {
  this.notify.error('Please select the Document Type');
  return;
}

1 个答案:

答案 0 :(得分:0)

Array.prototype.map()将遍历一个数组并返回另一个数组。

由于您不希望输出数组,因此使用的方式map()并非按预期使用。

出于纯粹的迭代目的,如果需要访问for迭代器索引,则应使用Array.prototype.forEach()或传统的i循环。

for (let i = 0; i < this.files.length; i++) {
  const doc = this.files[i];

  if (doc.selectedDocumentItem.Id === null) {
    this.DocumentSelected[i] = true;
    break; // <-- terminate for loop
  }
}