FANDOM


The following code sample adds indexOf and lastIndexOf methods to the standard Array object. Just add this section of code anywhere in your script and you will be able to call the methods on any Array you create.


Usage:

var myArray = new Array('a','b','c','b','d');
log(myArray.indexOf('c'));        //Returns 2
log(myArray.indexOf('c', 3));     //Returns -1
log(myArray.lastIndexOf('b');     //Returns 3
log(myArray.lastIndexOf('c', 3)); //Returns -1

/* Provides a method of searching for a specified value in an Array.
Returns the index of the first matching element or -1 if the element is not  found */
if (!Array.prototype.indexOf) {
	Array.prototype.indexOf = function(item, startIndex) {
		var len = this.length;
		if (startIndex == null)
			startIndex = 0;
		else if (startIndex < 0) {
			startIndex += len;
			if (startIndex < 0)
				startIndex = 0;
		}
		for (var i = startIndex; i < len; ++i) {
			var val = this[i] || this.charAt && this.charAt(i);
			if (val === item)
				return i;
		}
		return -1;
	};
}

/* Provides a method of searching for a specified value in an Array.
Returns the index of the last matching element or -1 if the element is not found */
if (!Array.prototype.lastIndexOf) {
	Array.prototype.lastIndexOf = function(item, startIndex) {
		var len = this.length;
		if (startIndex == null || startIndex >= len)
			startIndex = len - 1;
		else if (startIndex < 0)
			startIndex += len;
		for (var i = startIndex; i >= 0; --i) {
			var val = this[i] || this.charAt && this.charAt(i);
			if (val === item)
				return i;
		}
		return -1;
	};
}


Reference: Edit

Ad blocker interference detected!


Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.