jQuery.inArray() JQ Home  <<  Utilities  <<  jQuery.inArray()

Array value present.

Description

The jQuery.inArray() jQuery General utility method, returns a number denoting the index position within the array containing the specified value.

Shorthand version $.inArray()

  • The jQuery.inArray() jQuery General utility method will return the -1 if the value isn't found in the array

Syntax

Signature Description
jQuery.inArray( value, array [, fromIndex] )Return a number denoting the index position within the array containing the specified value, optionally passing an index value to start from.

Parameters

Parameter Description Type
valueThe value to search for.String
arrayAn array to search for value.Array
fromIndexThe index of the array to begin the search at . Default to 0, which will search the whole array.Number

Return

A Number object.

jQuery.inArray( value, array [, fromIndex] ) Example Utilities  <<  Top

Return a number denoting the index position within the array containing the specified value.

In the example below when we press the button the first time we create an array and then output a message showing the index position of the item with a value of 'tie using the $.inArray() general utility method. This outputs a message showing the index as 2. We then output another message showing the index position of the item with a value of 'tie using the $.inArray() general utility method. This outputs a message showing the index as -1. This is because the second time we set the fromIndex parameter to '3' and so the search starts from that index. The 'tie' item is in position 2 (index starts at 0) and therefore we get a value of -1 returned, which equates to 'not found'


$(function(){
  $('#btn18').one('click', function(){
    var arr0 = [ 'belt', 'boots', 'tie', 'bracers', 'shirt' ];
    $('#div14').append('index of tie in array is: ' +  $.inArray( 'tie', arr0 ) + '<br>');
    $('#div14').append('index of tie in array is: ' +  $.inArray( 'tie', arr0, 3 ));
  });
});

div14. Some initial text.


Press the button below to action the above code:

Related Tutorials

jQuery Intermediate Tutorials - Lesson 9 - jQuery General Utilities