I am trying to write the code of following algorithm
- I have an array of
active_id
(array) ID
coming from url (string)- if value of ID does not exist in active_id array
- run the function A()
- else do nothing.
Note - function A() should be run only once.
I tried writing the code
for (var i = 0; i < activeIds.length; i++) {
if (activeIds[i] != uid) {
A(); //This is running multiple times.
}
I tried using while loop
var i = 0;
while (activeIds[i] != uid) {
A(); //This is running multiple times again.
i++;
}
There is something i am missing. not able to figure it out.
-
Can you a add a fiddle link. People will be able to help you more easily.mechanicals– mechanicals2015年07月15日 11:38:07 +00:00Commented Jul 15, 2015 at 11:38
5 Answers 5
You can just use indexOf function which will return -1 if element is not exist on array and positive number start 0 till array (length -1) if element exist:
if (activeIds.indexOf(uid) == -1) {
A();
}
function A();
You can use indexOf
, like this:
if( activeIds.indexOf(id) < 0 ) A();
If you want to invoke function A()
only if the a particular ID (uid
) does not exist in your array activeIds
, you may want to alter your loop approach with this:
if (activeIds.filter(function(n){ return n===uid }).length==0){
A();
}
Where you have a definition of function A() ready to use already.
Side note You syntax with function A(){}
is just defining the function A but it's not going to run it. If you want to define and run it once, you may do:
(function A(){
// logic goes here
})();
-
-
Just to make sure it works even if the browsers don't support ES6 feature. I'm not sure if
activeIds.some(function(n){ return n===uid })
would produce better performance. Just wondering if it breaks as soon as it hits a truthy case.TaoPR– TaoPR2015年07月15日 12:22:00 +00:00Commented Jul 15, 2015 at 12:22 -
I thought too much BTW. Elements are just primitive numbers. :)TaoPR– TaoPR2015年07月15日 12:22:57 +00:00Commented Jul 15, 2015 at 12:22
-
filter and every are ES5 features. Only IE8 needs a shim...RobG– RobG2015年07月15日 12:27:03 +00:00Commented Jul 15, 2015 at 12:27
You can use array.indexof()
function in order to find the value.
It will look something like that:
if(activeIds.indexOf(uid) === -1){
A();
}
Try this, code.
var i=0;
var isMatchFound = false;
while (activeIds.length >= i) {
if(activeIds[i] ==uid){
isMatchFound = true;
break;
}
i++;
}
if(isMatchFound){
//Call Function A
A();
}
Hope this will help