In the Decoding jQuery series, we will break down every single method in jQuery, to study the beauty of the framework, as an appreciation to the collective/creative geniuses behind it.
jQuery.inArray()
In many programming languages, there is default inArray method, but in JavaScript, there isn’t a default one. jQuery has a handy inArray() method baked in. It searches for a specified value within an array and return its index (or -1 if not found).
Here is an example usage:
var arr = [ "Nokia", "Android", "Palm", "iPhone" ]; console.log(jQuery.inArray("Android", arr)); console.log(jQuery.inArray("Motorola", arr)); console.log(jQuery.inArray("Nokia", arr)); // returns // "Android" found at 1 // "Motorola" not found, so -1 // "Nokia" found at 0
Here is how the source code look like:
inArray: function( elem, array ) { if ( indexOf ) { return indexOf.call( array, elem ); } for ( var i = 0, length = array.length; i < length; i++ ) { if ( array[ i ] === elem ) { return i; } } return -1; }
As discussed in previous post, call() is a very useful build-in method of function object. One object can borrow methods from another object and use them as its own. Here is a breakdown of what it does:
1. check if indexOf is supported
if ( indexOf ) { //... }
2. if supported, it borrows the function and apply to inArray
if ( indexOf ) {
return indexOf.call( array, elem );
}
3. if not supported, it loops through the array and see if the element exists
for ( var i = 0, length = array.length; i < length; i++ ) { if ( array[ i ] === elem ) { return i; } }
4. if none of the above returns anything, it will return as not found
return -1;
By using indexOf as the first choice, it increases the performance of the script and make it execute faster.




This is actually out of date, as the current version of jQuery has added support for `fromIndex` as well as filtering against “holes” in sparse arrays.
https://github.com/jquery/jquery/blob/master/src/core.js#L685-705
Thanks for the highlight, I will probably update the post some day with these new changes. :)
Pingback: JavaScript Magazine Blog for JSMag » Blog Archive » News roundup: Node causes cancer, node cures cancer!
Pingback: Weekly Links– 2011_35 (50 for Web Devs & Other Geeks) :MisfitGeek (Joe Stagner)