RSS | Archive | Random | E-mail

About

Hi, I'm Christian Castelli, a 28 years old italian programmer located in Pisa (Italy). Here I post small snippets of code which can be useful in my work.

Links

Codepuzzling main site
Development site
ByteStrike italian blog
Follow me on Twitter

My Life Style

while(passion) {
  try {
    myLife.run();
  }catch(LifeExceptions) {  
    stronger++;
    continue;
   }
}

Following

22 September 09

[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.

Comments (View)
blog comments powered by Disqus
Themed by Hunson. Originally by Josh