VirtualMV/JavaScript/Arrays

From WikiEducator
Jump to: navigation, search




Introduction

Overview

  • An array is an object used to store a set of values under a single variable name


VmvIcon Objectives.png

By the end of this page you will be able to:

  • Understand JavaScript arrays

Creating an array

  • Array elements are referred to by an index staring at 0
  • Arrays are created using the new keyword
var arrParts= new Array(); // create an array of no fixed size
var computers=new Array(5); //Create an array containing 5 rows (0..4)
  • Data can be assigned to arrays by index or assignment (arrComputers1) or in one line (arrComputers2)
var arrComputers1=new Array(5);
  arrComputers1[0]="dell";
  arrComputers1[1]="ibm";
  arrComputers1[2]="apple";
  arrComputers1[3]="hp"
  arrComputers1[4]="compaq"
 
var arrComputers2 =new Array("dell","ibm","apple","hp","compaq");

This can be handy when you want to convert a month number to a month name e.g.

var arrMonth =new Array("", "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");

Question: Why is the first value ""?

Online tutorials

Simple array example (js7_01)

<html>
<head><title>JavaScript (js7_01)</title></head>
<body>
<script type="text/javascript">
var arrName = new Array(6);
  arrName[0] = "Steve";
  arrName[1] = "David";
  arrName[2] = "Frina";
  arrName[3] = "Michael";
  arrName[4] = "John";
  arrName[5] = "Kim";
for (intI=0; intI<6; intI++){
   document.write(intI+":"+ arrName[intI] + "<br />");
}
document.write("--------------"+ "<br />");
for (intI=5; intI>=0; intI--){
   document.write(intI+":"+ arrName[intI] + "<br />");
}
</script>
</body>
</html>

Example js7_01

Array properties

 
PropertyMeaning (Returns ...)
lengththe number of elements in an array. This property is assigned a value when an array is created
concat()an array concatenated of two arrays
join()a string of all the elements of an array concatenated together
reverse()the array reversed
slice()a specified part of the array
sort()a sorted array

Math and array example (js7_02)

<html><head><title>JavaScript Array (js7_02)</title>
<script type="text/javascript">
function fnNumOrdA(a, b){ return (a-b); } // Chapman(2008)- numerical sort
function fnCalc() {
  frmRef=document.frmSort;
  var arrNum = new Array(3);
  arrNum[0] = parseFloat(frmRef.num1.value);
  arrNum[1] = parseFloat(frmRef.num2.value);
  arrNum[2] = parseFloat(frmRef.num3.value);
  arrSorted=arrNum.sort();
  frmRef.sort.value=arrSorted;
  arrSorted = arrNum.sort( fnNumOrdA );
  frmRef.sortN.value=arrSorted;
  intMiddle=(Math.floor(arrNum.length/2));
  vntMedian=arrSorted[intMiddle];
  frmRef.median.value=vntMedian; 
}
</script>
</head>
<body><h4>Enter three numbers</h4>
<form name="frmSort">
Number 1:<input name="num1" type="number" />21<br>
Number 2:<input name="num2" type="number" />1<br>
Number 3:<input name="num3" type="number" />7<br>
 <input type="button" value="Calculate" onClick="fnCalc()" /><br />
Text Sort:<input name="sort" type="number" /> (sorts 1,21,7)<br />
Number Sort:<input name="sortN" type="number" /> (sorts 1,7,21)<br />
Median:<input name="median" type="number" /> 
</form></body></html>

Ref: Chapman (2008)[3]

Example js7_02


Array split method

The array split method allows you to take a string and split it into an array based on a specified character. In the example following I will use the comma (,) to split a name in lastname, firstname format and reverse the order. I have also added something a little special :)

Array.split .. example (jsArr_Split.htm)

<html>
<head>
<title>JavaScript Array Split example</title>
</head>
<body>
  <div style="color: #0000FF">
    <script type="text/javascript">
	var strText = "Bunny, Floptical";
	var arrName = strText.split(",");
	document.write('Hi '+arrName[1] +" " +arrName[0] + " " + "\u2740");
	</script>
  </div>
</body>
</html>

Note: Just to show you how I have asked a unicode character to be displayed (\u2740) which is a flower. Unicode Inc (2009)[4]gives pdf files for all the unicode characters (I used the Dingbats one for the flower).

Example jsArr_Split.htm ?????????????????????????????????????????? (upload) ?????????


VmvIcon Activity.png

: Inverting a date to standard date format

Use the array split method to convert a date entered as dd/mm/yyyy to yyyymmdd.

Array multi-dimension

A two-dimensional array is created simply by building on a "normal" array. Constructing a two-dimensional array requires that we declare another array on top of EACH of the "stems" (myarray[0], myarray[1]...)

var arrRow=new Array(3)  // creates 3 rows (0,1,2)
for (intI=0; intI < 3; intI++) 
arrRow[intI]=new Array(2) // creates 2 columns (0,1)

As you can see, what we need to do is  declare a new array on top of each individual array "stem". The translation of this idea to actual codes, as you will see, is actually very simple

Multidimensional array example 1(js7_03)

<html>
<head><title>JavaScript multidimensional array (js7_03) </title></head>
<body>
<script type="text/javascript">
  var intCol1 = 0
  var intCol2 = 1
  var arrRow = new Array(3)    // create 3 rows(0,1,2)
    for (i=0; i <3; i++){
      arrRow[i] = new Array(2) // create 2 columns (0,1)
    }
  arrRow[0][0] = "(1,1)"; arrRow[0][1] = "(1,2)";
  arrRow[1][0] = "(2,1)"; arrRow[1][1] = "(2,2)";
  arrRow[2][0] = "(3,1)"; arrRow[2][1] = "(3,2)";
  for (i = 0; i < arrRow.length; i++) {
    document.write(arrRow[i] [intCol1]);
    document.write(arrRow[i] [intCol2]);
    document.write("<br />");
  }
</script>
</body>
</html>

Result

(1,1)(1,2)
(2,1)(2,2)
(3,1)(3,2)

Example js7_03


Multidimensional array example 2(js7_04)

<html>
<head>
<title>JavaScript Multi-dimensional Array (js7_04)</title>
</head>
<body>
<script language="JavaScript">
 /* First make up an array for each row ----------------*/
 part1 = new Array("Brake pads","39D48G",78);
 part2 = new Array("Brake shoes","7D9UK3",45);
 part3 = new Array("Rotors","97WOST",14);
 part4 = new Array("Seals","2DPLUG",15);
 /* Now join up all the row arrays into one big array -- */
 brakeParts = new Array(part1,part2,part3,part4);
 /* Now print them out in a table ----------------------- */
 document.write('<table border=1>')
 for (intI=0;intI<4;intI++){
   document.write('<tr>')
   for (intJ=0;intJ<3;intJ++) {
     document.write('<td width="150">' + brakeParts[intI][intJ] +'</td>')
   }
   document.write('</tr>')
 }
 document.write('</table>')
</script>
</body>
</html>

Result

Brake pads39D48G78
Brake shoes7D9UK345
Rotors97WOST14
Seals2DPLUG15

Example js7_04


VmvIcon References.png References

  1. w3schools (2009).JavaScript Array Object. Retrieved May 5, 2009 from http://www.w3schools.com/JS/js_obj_array.asp
  2. w3schools (2009).JavaScript Array Object Reference. Retrieved May 5, 2009 from http://www.w3schools.com/jsref/jsref_obj_array.asp
  3. Chapman, S. (2008) Numeric Array Sort. Retrieved May 15, 2008, from http://javascript.about.com/library/blsort.htm
  4. Unicode, Inc (2009) Unicode 5.2 Character Code Charts. Retrieved November 1, 2009 from http://unicode.org/charts/

virtualMV  |  Superquick wiki guide  |  Please give me some feedback

VirtualMV/JavaScript/Arrays. (2024). In WikiEducator/VirtualMV wiki. Retrieved November 5, 2024, from http:https://wikieducator.org/VirtualMV/JavaScript/Arrays    (zotero)