首页 > 解决方案 > 如何检查javascript数组是否包含具有特定值的属性,如果是则返回true

问题描述

我有一个角度的选择 - 选项,我需要检查与数据库中的 id 具有相同 id 的值,所以我尝试了这样的事情:

isDropdownValueSelected(amf: ApplicationModuleForm): boolean {
    for (let i = 0; i < this.role.applicationForms.length; i++) {
      if (this.role.applicationForms[i].id == amf.id) {
        return true;
      }
      else {
        return false;
      }
    }
 }

我的角度部分:

<div class="col-lg-9">
     <select id="applicationModuleFormSelect" name="applicationModuleFormSelect" class="form-control multiselect-select-all" multiple="multiple" data-fouc>
        <option *ngFor="let amf of appModuleForms;" [value]="amf.id" [selected]="isDropdownValueSelected(amf)">{{amf.title}}</option>
     </select>
</div>

所以基本上我想在选项中循环每个id,如果我在我的数组中发现类似的我会返回true,因为数组this.role.applicationForms保存来自数据库的值,但不幸的是这不起作用,在下拉列表中没有选择任何内容,我用控制台日志测试它说即使有 3 个值,也只存在 1 个值。

谢谢大家干杯

标签: javascripthtmlarraysangularecmascript-6

解决方案


Maybe you need to move the false value to the end for returning, because every return statement ends the function.

isDropdownValueSelected(amf: ApplicationModuleForm): boolean {
    for (let i = 0; i < this.role.applicationForms.length; i++) {
        if (this.role.applicationForms[i].id == amf.id) {
            return true;
        }
    }
    return false;
}

推荐阅读