[英]Check if object value inside array, already exists in a different array of objects?
[英]Check if value exists in an object in array of objects
我正在尝试编写以下算法的代码
active_id
数组(数组) ID
(字符串) 注意 -函数A()应该只运行一次。
我尝试编写代码
for (var i = 0; i < activeIds.length; i++) {
if (activeIds[i] != uid) {
A(); //This is running multiple times.
}
我尝试使用while循环
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();
如果仅在数组activeIds
中不存在特定ID( uid
)的情况下才想调用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();
}
希望这会有所帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.