BWSnippet

jQuery inArray

jQuery inArray

How to check if something is in an array in jQuery

In Array - jQuery be sure to check for -1


var arrayOfCoolThings = [];
arrayOfCoolThings[ 0 ] = "Robots";
arrayOfCoolThings[ 1 ] = "Grapes";
arrayOfCoolThings[ 3 ] = "Touch Screens";
arrayOfCoolThings.push( "Solar Lights" );

if($.inArray( "Solar Lights", arrayOfCoolThings) > -1 )
    console.log("In Array " );
else
	console.log(" Not In Array :( Wrong Answer");


If it is not in the array, it will return -1. You need to check for that otherwise it will be interpreted as in the array even if 0 is returned. This is because 0 is a valid index.

Tags

jQuery inArray