Thursday, May 20, 2010

Javascript: Make indexOf function working in IE

The indexOf function is a recent addition to the ECMA-262 standard and newly introduced in JavaScript 1.6, hence it may not work in some browsers. You can work around this by inserting the following piece of code at the beginning of your scripts.

Note: This function will work in FF1.5 or above, because this algorithm is exactly the one used in Firefox and SpiderMonkey(is the code-name for the Mozilla's C implementation of JavaScript).

if(!Array.indexOf) {
  Array.prototype.indexOf = function(obj) {
    for(var i = 0; i < this.length; i++) {
      if(this[i] == obj) { return i; }

    return -1;

No comments:

Post a Comment