Posts Tagged ‘indexOf’

Posted by 6bytes at 30, August, 2010

Category: JavaScript

Tags: , , , , , ,

Recently I’ve been working on a project with HTML5 <video> tag event handling and I needed to check if an element exists in the array. Quick googling resulted in neat native JavaScript method Array.indexOf. It returns the first index at which a given element can be found in the array, or -1 if it is not present. It all worked just fine in Firefox, Chrome and such.
Why wasn’t I surprised when my script behaved a bit weird in Internet Explorer. After many hours of “fun” with IE JavaScript debugger, I found that none of IE’s support the Array.indexOf method.

Thanks to this post I was able to quickly fix it by adding below code to my script.

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

and the world was beautiful again.