Friday, August 3, 2012

Javascript: adding array methods

I used a.indexOf(“a”) to find the position of “a” inside an array. Turns out this an extension not supported by Internet Explorer.

But from http://stackoverflow.com/questions/2790001/fixing-javascript-array-functions-in-internet-explorer-indexof-foreach-etc we see how easy it is to add this function in case it is missing.

// Add ECMA262-5 Array methods if not supported natively
//
if (!('indexOf' in Array.prototype)) {
   
Array.prototype.indexOf= function(find, i /*opt*/) {
       
if (i===undefined) i= 0;
       
if (i<0) i+= this.length;
       
if (i<0) i= 0;
       
for (var n= this.length; i<n; i++)
           
if (i in this && this[i]===find)
               
return i;
       
return -1;
   
};
}



Pretty cool. Of course here it helps that Javascript is not type-checked (otherwise one would need generics or something like that).

No comments:

Post a Comment