【问题标题】:Search array for at least 1 match and return true在数组中搜索至少 1 个匹配项并返回 true
【发布时间】:2019-06-05 18:15:50
【问题描述】:

我需要测试我的 JSON 响应以确保至少 1 个对象包含 isKey:true 值,此时 hasKey 的全局变量设置为 true。

我相信 SOME 方法在这种情况下会有所帮助,但它似乎只在本地级别进行测试,所以如果我在 console.log 中得到:true,false,true,true... 等

我只想针对整个模型确定真假。

您可以在下面看到一个工作功能的基础,但我不认为它是有效的,所以任何建议都可以改进它。

 checkKeys() {

    let checkTest: boolean = false;

    this.modalData.columnPermissions.some(function (item) {

      if (item.isKey) {
        checkTest = true;
      }
    });

    this.modalData.hasKey = checkTest;

  }

【问题讨论】:

标签: javascript typescript


【解决方案1】:

你可以直接赋值some的结果。

checkKeys() {
    this.modalData.hasKey = this.modalData.columnPermissions.some(function (item) {
        return item.isKey;
    });
}

【讨论】:

    【解决方案2】:

    你有正确的功能,你只是用错了。

    this.modalData.hasKey = this.modalData.columnPermissions.some(function (item) {
      return item.isKey;
    });
    

    'some' 函数获取返回值并在返回值为 true 时立即停止运行。

    'every' 函数获取返回值并在其中一个为 false 时立即停止运行。

    【讨论】:

      猜你喜欢
      • 2013-07-29
      • 1970-01-01
      • 2018-05-09
      • 1970-01-01
      • 2021-09-12
      • 1970-01-01
      • 2017-11-27
      • 2021-11-16
      • 2013-06-04
      相关资源
      最近更新 更多