如何检查javascript数组是否持有具有特定值的属性,如果是则返回true

时间:2019-02-05 10:33:11

标签: javascript html arrays angular ecmascript-6

我在angular中有一个select-选项,我需要检查与数据库中的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个值。

谢谢大家 干杯

5 个答案:

答案 0 :(得分:1)

由于每个return语句都会终止该函数,因此可能需要将false值移到末尾以返回。

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;
}

答案 1 :(得分:1)

此功能仅在第一个元素的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;
        }
    }
    return false;
}

答案 2 :(得分:0)

假设applicationForms是一个数组,则可以使用方法some

isDropdownValueSelected(amf: ApplicationModuleForm): boolean {
  return this.role.applicationForms.some(({id}) => id === amf.id);
}

答案 3 :(得分:0)

使用some运算符,而不是在元素上循环:

isDropdownValueSelected(amf: ApplicationModuleForm): boolean {
    return this.role.applicationForms.some(e => e.id === amf.id);
}

答案 4 :(得分:0)

您不需要.carousel-title { font-family: 'PT_Serif-Web-BoldItalic'; font-size: 20px; display: grid; width: 100%; align-items: center; text-align: center; grid-template-columns: minmax(20px, 1fr) auto minmax(20px, 1fr); grid-gap: 20px; &:before, &:after { content: ''; border-top: 1px solid; } } .carousel-wrapper { width: 100%; display: flex; justify-content: center; .widget { margin: 0 10px; } .arrow { cursor: pointer; align-self: center; margin: 40px; } .carousel { display: flex; flex-direction: row; max-width: 750px; overflow: hidden; transform: translateX(100%); &.is-reversing { transform: translateX(-100%) } &.is-set { transform: none; transition: transform 0.5s cubic-bezier(0.23, 1, 0.32, 1); } @media(max-width: 1049px){ width: 500px; } @media(max-width: 800px){ width: 240px; } } } .item { background-color: #f6f6f6; display: flex; font-size: 30px; justify-content: center; align-items: center; min-width: 230px; height: 400px; margin: 10px } body { overflow: hidden } 循环:

<Carousel title="My carousel" items={[1,2,3,4,5,6,7,8,9]} />