DZone 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

Snippets has posted 5883 posts at DZone. View Full User Profile

Firefox1.5 Array Extra Methods For Other Browsers

09.15.2005
| 7530 views |
  • submit to reddit
        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 <a href="http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Array#Methods">here</a>

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

Snippets Manager replied on Mon, 2012/05/07 - 2:15pm

Of course, I know. However, I think that advantages are larger than disadvantages.

Snippets Manager replied on Mon, 2012/05/07 - 2:15pm

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 )...