Javascript Function: array_search()

Was writing some javascript for a friend and developed these simple functions for searching javascript arrays.
Becomes pretty useful when your working with select html boxes and arrays in javascript.

function array_search (array,val) {
for (var i = 0; i < array.length; i++) {
if (array[i] == val) {
return i;
}
}
return false;
};
 
function array_search_key(array,num) {
if (array[num]) return true;
return false;
};

An example of the usage:

var myArray = [ 10, 20, 30, 40, 50, 60 ];
alert( array_search( myArray, 30 ) );
// Output: 2

Keep in mind that arrays in most langauges start from 0.

for_example( myArray[0] ); // Outputs 10

Hope this function comes in use some day.

If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.

Comments

realy good work, tnx a lot mate..

Leave a comment

(required)

(required)