Categories

Tools

bitdefender

1&1 Web Hosting

Example of how to use arrays in Javascript


Code:

<script type="text/javascript">
	// Create an array of strings
	var customers = new Array(  "Steven",
								"Barbara", 
								"Bill",
								"Carlos",
								"Miriam", 
								"Elena",
								"Tony");

	// Print the content of array
	PrintArray(customers, "initial state");

	// Add some items in the array
	customers = customers.concat("Sara");
	customers = customers.concat("Daisy");
	customers = customers.concat("Daniel");

	// Print the content of array
	PrintArray(customers, "after concat");

	// Reverse the content of the array
	customers.reverse();
	PrintArray(customers, "after reverse");

	// Sort the array
	customers.sort();
	PrintArray(customers, "after sort");

	// Extract the array elements and put them in a variable
	var allCustomers = customers.join(", ");
	document.write("Content of allCustomers (after join) :<br />" + allCustomers + "<br />");

	// Print the content of the array
	function PrintArray( a , t) {
		document.write("Content of array ("+ t +"):<br />");
		for (n = 0; n < a.length; n++) {
			document.write(a[n] + "<br />");
		}
		document.write("<br />");
	}
</script>

Result:

Content of array (initial state):
Steven
Barbara
Bill
Carlos
Miriam
Elena
Tony

Content of array (after concat):
Steven
Barbara
Bill
Carlos
Miriam
Elena
Tony
Sara
Daisy
Daniel

Content of array (after reverse):
Daniel
Daisy
Sara
Tony
Elena
Miriam
Carlos
Bill
Barbara
Steven

Content of array (after sort):
Barbara
Bill
Carlos
Daisy
Daniel
Elena
Miriam
Sara
Steven
Tony

Content of allCustomers (after join):
Barbara, Bill, Carlos, Daisy, Daniel, Elena, Miriam, Sara, Steven, Tony

Posted in Javascript by MdmSoft

If our work has been of help, you can help us with a small donation...
Our programmers will thank you!



All information contained in this web site are the property of MdmSoft. The information is provided "as is", MdmSoft will not be liable for any misuse of the code contained in these pages, nor can it be for inaccuracies, grammatical errors or other factors that may have caused damage or lost earnings. MdmSoft is not responsible for the content of comments posted by users.
The examples in this area have the educational and demonstration purposes only, and may be copied only for your reference, but cannot be used for commercial purposes, or for any other purpose, without the express written consent of MdmSoft.
MdmSoft also reserves the right to change, without notice, to your liking this web site, the pages and its sections, and may suspend temporarily or definitely the various services included on this site.
While using this site, you agree to have read and accepted our Terms of Service and Privacy Policy.