检查对象数组中的对象中是否存在value

Check if value exists in an object in array of objects

本文关键字:对象 存在 value 是否 检查 数组      更新时间:2023-09-26

我正在尝试编写以下算法的代码

    我有一个数组active_id (array)
  • ID来自url (string)
  • 如果active_id数组中ID的值不存在
    • 运行函数A()

注意 -函数A()应该只运行一次。

我试着写代码

for (var i = 0; i < activeIds.length; i++) {
    if (activeIds[i] != uid) {
         A();  //This is running multiple times.
    }

我尝试使用while loop

var i = 0;
while (activeIds[i] != uid) {
     A();  //This is running multiple times again.
    i++;
}

我错过了一些东西。

您可以使用indexOf函数,如果数组中不存在元素,则返回-1;如果元素存在,则从0开始,直到数组(长度-1):

if (activeIds.indexOf(uid) == -1) {
    A();  
}
function A(); 

您可以使用indexOf,像这样:

if( activeIds.indexOf(id) < 0 ) A();

如果您想仅在特定ID (uid)不存在于您的数组activeIds中时调用function A(),您可能需要这样更改您的循环方法:

if (activeIds.filter(function(n){ return n===uid }).length==0){
    A();
}

函数a()的定义已经准备好使用了。

边注您与function A(){}的语法只是定义函数A,但它不会运行它。如果你想定义并运行它一次,你可以这样做:

(function A(){
   // logic goes here
})();

您可以使用array.indexof()函数来查找值。它看起来像这样:

if(activeIds.indexOf(uid) === -1){
    A();
}

试试这个,代码。

var i=0;
var isMatchFound = false;
while (activeIds.length >= i) {
  if(activeIds[i] ==uid){
    isMatchFound = true;
    break;
}
 i++;
}
if(isMatchFound){
   //Call Function A
    A();
}

希望对大家有所帮助