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