【问题标题】:Function to detect if specific value exists in an array of objects in javascript [duplicate]用于检测特定值是否存在于javascript中的对象数组中的函数[重复]
【发布时间】:2015-04-26 22:58:00
【问题描述】:

我有一个如下所示的数组:

userInterests [
  {
    "Status": "Interested",
    "$id": "-JncIGjhkuEx1Hq6Lzax",
    "$priority": null
  }
  {
    "Status": "Interested",
    "$id": "-TDIEGjhkuEx1Hq6Lzax",
    "$priority": null
  }
]

我需要一个布尔函数,如果 id 匹配则返回 true 或 false,所以这样的函数:

function isAnIDInArray(id) {

}

这样

isAnIDInArray(-JncIGjhkuEx1Hq6Lzax);

会返回真

【问题讨论】:

标签: javascript arrays object


【解决方案1】:

您的函数必须遍历数组中的所有对象并检查每个 ID。所以是这样的:

function isAnIDInArray(id, array) {
    var i;
    for(i = 0; i < array.length; i++) {
        If(array[i].$id == id) {
            return true;
        }
    }
    return false;
}

不确定是否可以在 javascript 语法中使用“$”。

【讨论】:

    猜你喜欢
    • 2022-07-20
    • 2021-11-27
    • 2014-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-02
    • 2015-08-03
    • 1970-01-01
    相关资源
    最近更新 更多