jQuery.inArray() in jQuery

 

jQuery.inArray( value, array ) : The $.inArray() method is similar to JavaScript’s native .indexOf() method in that it returns -1 when it doesn’t find a match. If the first element within the array matches value, $.inArray() returns 0.

Because JavaScript treats 0 as loosely equal to false (i.e. 0 == false, but 0 !== false), if we’re checking for the presence of value within array, we need to check if it’s not equal to (or greater than) -1.

Report the index of some elements in the array.

<!DOCTYPE html>
<html>
<head>
  <style>
  div { color:blue; }
  span { color:red; }
</style>
  <script src="/scripts/jquery-1.4.js"></script>
</head>
<body>
	
<div>"John" found at <span></span></div>
<div>4 found at <span></span></div>
<div>"Karl" not found, so <span></span></div>
<script>var arr = [ 4, "Pete", 8, "John" ];

$("span:eq(0)").text(jQuery.inArray("John", arr));
$("span:eq(1)").text(jQuery.inArray(4, arr));
$("span:eq(2)").text(jQuery.inArray("Karl", arr));

</script>
</body>
</html>

Leave a Reply

Your email address will not be published. Required fields are marked *