Old code: JavaScript x-browser arrays (2005, 2010)

Last update: 2010-12-09

This block of code is deprecated, I'm only keeping it for archival purposes, see below for a more up-to-date equivalent

/*
 * Public Domain
 *
 * Created by Toni Corvera <outlyer@outlyer.net>, 2005
 *
 * Defines Array.find, and Array.merge
 */
// int Array.find(Object)
if (!Array.indexOf) {/*IE has no indexOf*/
	Array.prototype.find = function(what) {
		for (var i=0; i<this.length; ++i) {
			if (this[i]==what) {
				return i;
			}
		}
		return -1;
	}
}
else {
	Array.prototype.find=Array.prototype.indexOf;
}
// void Array.merge(Array)
Array.prototype.merge = function(a) {
	for (var i=0;i<a.length;++i) {
		this.push(a[i]);
	}
}

Old location: http://p.outlyer.net/graveyard/net_outlyer_arrays.js.

Array.find and Array.merge are equivalent to the standard methods Array.indexOf and Array.concat.

  • Array.concat was added to IE in version 4.0
  • Array.push was added on version 5.5.
  • Array.indexOf is not so widely supported (IE6 doesn't support it -I'm yet to try higher versions-, Chrome does)

Updated:

// int Array.indexOf(Object)
if (!Array.indexOf) { /*IE has no indexOf*/
	//This prototype is provided by the Mozilla foundation and
	//is distributed under the MIT license.
	//http://www.ibiblio.org/pub/Linux/LICENSES/mit.license
	Array.prototype.indexOf = function(elt /*, from*/) {
		var len = this.length;
	    var from = Number(arguments[1]) || 0;
		from = (from < 0) ? Math.ceil(from) : Math.floor(from);
	    if (from < 0)
			from += len;
		for (; from < len; from++) {
			if (from in this && this[from] === elt)
		        return from;
		}
		return -1;
	};
}
if (!Array.push) {
	Array.prototype.push = function(e) {
		this[this.length] = e;
		return this.length;
	};
}

References:


Discover more from OutlyerNet

Subscribe to get the latest posts to your email.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top