kevin ver kevin ver - 5 months ago 43
Javascript Question

Javascript check if array contains value

I have a array with numbers

ListIds
and i like to check if it contains my user id
myId
but for some strange reason it keeps on returning
no match
what I'm i doing wrong here?

var ListIds = object.ListFolowers; // = 33,34,35
var myId = userProfileID2_class; // = 33

if(ListIds.indexOf(myId)>=0){
debug_log('Value exist');
} else {
debug_log('no match');
}


ps if i change
if(ListIds.indexOf(myId)>=0)
to
if(ListIds.indexOf(33)>=0)
it works...

fixit it by adding a
+
to
if(ListIds.indexOf(+myId)>=0){

Answer

@Rohit Shedage's guess was correct.

Your problem here is that userProfileID2_class is a string value and by doing +myId to the string type, the javascript engine would have automatically converted the string to an integer before applying indexOf to it.

You might want to consider fixing the root problem cause instead. That is, storing your Id as an integer/ converting it to integer before setting it.