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

Python contextlib for Timing Python code

If you've ever found yourself needing to measure the execution time of specific portions of your Python code, the `contextlib` module o...