Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Web
Expertise: Advanced
Sep 10, 2001

Extend the Array JavaScript Object with Your own Functions


The JavaScript Array intrinsic object (and others) can be extended to include user-defined functions in the object definition. These extensions can be placed in a .js file and included in all pages to create a common library.

In the example below, the Array object has been extended with a contains function that checks the array for the specified string. The caseSensitive global variable is used to indicate case comparison. All instantiated arrays will now be able to use the .contains method.
 
<html><head><title>
Array.contains</title>
<script language="JavaScript"><!--
var caseSensitive = true;

function Array_Contains(strTest) {
	for (var i=0; i<this.length; i++) {
		// Case sensitive version...
		if (caseSensitive == false) {
			if (this[i] == strTest)
				return true;
		} else { //Case insensitive version...
			if (String(this[i]).toLowerCase() 
== String(strTest).toLowerCase())
				return true;
		}
	}
	return false;
}
Array.prototype.contains = Array_Contains;

var arySample = new Array("1", "Two", "3");
//--></script>
<body>
<input type="text" id="txtCriteria" 
value=""><br>
<input type="button" value="Find"
onclick="alert(arySample.contains
(window.txtCriteria.value));">
</body></html>
Fred Hirschfeld
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date