[JS] How to extend Array object to get the index of an its value
The code is self explanatory: you have an array and you want to know what index has the element “pippo” or “5”. So I extended the array object with prototype keyword to scan the array and to return the index if found, -1 otherwise.
var points = [56,12,36];
Array.prototype.getIndex = function(aVal)
{
for(item in this)
if(aVal == this[item])
return item;
return -1;
}
console.log(points.getIndex(36));
If you have Firefox or Safari (maybe in IE8 too, I dunno), watch at the console and you’ll see2 as result.