Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Firefox1.5 Array extra methods for other browsers (See related posts)

Array.prototype extension

- Array#forEach
- Array#map
- Array#filter
- Array#every
- Array#some
- Array#indexOf
- Array#lastIndexOf

for IE, Opera, and older Firefox.(I can't test safari)
you can find reference and sample code here

if(!Array.prototype.forEach){
Array.prototype.forEach = function(callback,thisObject){
	for(var i=0,len=this.length;i<len;i++)
		callback.call(thisObject,this[i],i,this)
}
Array.prototype.map = function(callback,thisObject){
	for(var i=0,res=[],len=this.length;i<len;i++)
		res[i] = callback.call(thisObject,this[i],i,this);
	return res
}
Array.prototype.filter = function(callback,thisObject){
	for(var i=0,res=[],len=this.length;i<len;i++)
		callback.call(thisObject,this[i],i,this) && res.push(this[i]);
	return res
}
Array.prototype.indexOf = function(searchElement,fromIndex){
	var i = (fromIndex < 0) ? this.length+fromIndex : fromIndex || 0;
	for(;i<this.length;i++)
		if(searchElement === this[i]) return i;
	return -1
}
Array.prototype.lastIndexOf = function(searchElement,fromIndex){
	var max = this.length-1;
	var i = (fromIndex < 0)   ? Math.max(max+1 + fromIndex,0) :
			(fromIndex > max) ? max :
			max-(fromIndex||0) || max;
	for(;i>=0;i--)
		if(searchElement === this[i]) return i;
	return -1
}
Array.prototype.every = function(callback,thisObject){
	for(var i=0,len=this.length;i<len;i++)
		if(!callback.call(thisObject,this[i],i,this)) return false;
	return true
}
Array.prototype.some = function(callback,thisObject){
	for(var i=0,len=this.length;i<len;i++)
		if(callback.call(thisObject,this[i],i,this)) return true;
	return false
}
}

Comments on this post

jonasraoni posts on Sep 20, 2005 at 00:58
Hi, just to express my opinion about prototyping the "Global Objects" ;]

In my opinion, it's a bad approach to add things to the prototype ;]

You know...

for( var i in x )...
ma.la posts on Sep 26, 2005 at 18:56
Of course, I know.




However,
I think that advantages are larger than disadvantages.

You need to create an account or log in to post comments to this site.


Click here to browse all 5147 code snippets

Related Posts